【问题标题】:Is there a simple way to convert a list of integers to a formatted string in Python? [duplicate]有没有一种简单的方法可以将整数列表转换为 Python 中的格式化字符串? [复制]
【发布时间】:2018-02-01 11:29:13
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

标签: python list tostring


【解决方案1】:

不是很简单,但这会产生预期的结果:

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

【讨论】:

  • 确实不简单,但是完全符合预期,非常感谢!
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多