有没有一种简单的方法可以将整数列表转换为 Python 中的格式化字符串?

Is there a simple way to convert a list of integers to a formatted string in Python?

我正在编写一个生成整数列表的程序,例如:

[2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20]

此列表可能很长,但它包含许多连续的值,如本例所示。

为了将其存储(在数据库中),我想将其转换为格式化字符串,格式如下:

"2,5-10,15,18-20"

我已经想到了一个解决方案,它遍历整个列表以检测连续值并构建字符串。

我的问题是:在 Python 中是否有另一种更简单的方法来进行这种转换?

据我所知,您提出的解决方案是唯一的选择:

  • 迭代项目,存储序列中的第一个数字
  • 如果下一个数字不是序列中的下一个,构建 "first-last" 字符串并添加到序列列表。

没有理由存储为字符串,可以存储为字符串列表

并不十分简单,但这会产生预期的结果:

from itertools import groupby, count
from operator import itemgetter

a = [2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20]
formatted = ','.join(str(x) if x == y else "{}-{}".format(x, y) for x, y in [itemgetter(0, -1)(list(g)) for k, g in groupby(a, lambda n, c = count(): n - next(c))])

print(formatted)

其中显示:

2,5-10,15,18-20