python - 格式化连续数字

标签 python int format

我正在尝试使用 Python 格式化整数列表,但在实现我想要的结果时遇到了一些困难。

输入是一个排序的整数列表:

list = [1, 2, 3, 6, 8, 9]

我希望它的输出是一个看起来像这样的字符串:

outputString = "1-3, 6, 8-9"

到目前为止,我设法实现的是:

outputString = "1-2-3, 6, 8-9"

我无法告诉我的代码忽略已经连续的 Int。

到目前为止,这是我的代码:

def format(l):
    i = 0
    outputString = str(l[i])
    for x in range(len(l)-1):
        if l[i + 1] == l[i]+1 :
            outputString += '-' + str(l[i+1])
        else :
            outputString += ', ' + str(l[i+1])
        i = i + 1
    return outputString

感谢您的帮助和见解:)

最佳答案

您可以像这样使用 itertools 模块中的 groupbycount:

编辑:

感谢 @ason​​gtoruin 评论。要从输入中删除重复项,您可以使用:sorted(set(a))

from itertools import groupby, count

a = [1, 2, 3, 6, 8, 9]
clustered = [list(v) for _,v in groupby(sorted(a), lambda n, c = count(): n-next(c))]

for k in clustered:
    if len(k) > 1:
        print("{0}-{1}".format(k[0], k[-1]))
    else:
        print("{0}".format(k[0]))

输出:

1-3
6
8-9

或者也许你可以做这样的事情以获得漂亮的输出:

from itertools import groupby, count

a = [1, 2, 3, 6, 8, 9]
clustered = [list(v) for _,v in groupby(sorted(a), lambda n, c = count(): n-next(c))]
out = ", ".join(["{0}-{1}".format(k[0], k[-1]) if len(k) > 1 else "{0}".format(k[0]) for k in clustered ])

print(out)

输出:

1-3, 6, 8-9

更新:

我猜,使用 itertools 模块可能会使许多 Python 的新开发人员感到困惑。这就是为什么我决定重写相同的解决方案而不导入任何包并尝试显示 groupbycount 在幕后所做的事情:

def count(n=0, step=1):
    """Return an infinite generator of numbers"""
    while True:
        n += step
        yield n


def concat(lst):
    """Group lst elements based on the result of elm - next(_count)"""
    _count, out = count(), {}
    for elm in sorted(lst):
        c = elm - next(_count)
        if c in out:
            out[c].append(elm)
        else:
            out[c] = [elm]
    return out


def pretty_format(dct):
    for _, value in dct.items():
        if len(value) > 1:
            yield '{}-{}'.format(value[0], value[-1])
        else:
            yield '{}'.format(value[0])


lst = [1, 2, 3, 6, 8, 9]
dct = concat(lst)
formatted = list(pretty_format(dct))
print(formatted)

输出:

['1-3', '6', '8-9']

关于python - 格式化连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42841514/

相关文章:

带有 FancyBox 格式的 Jquery cookie 插件 FancyBox

python - 在 SQLite 或 Python 中聚合

python - 如何在 Python 中捕获 EINTR?

python:我可以将字符串格式化运算符与类的 getter 方法一起使用吗?

java - java中int到double的转换

C 基本 scanf 不工作

python - 在python中将某些内容从一个文件写入另一个文件

python - pygtk:在 gtk.gdk.Pixbuf 上画线

python - 如何在django View 中检查数据是否为 'null'?

java - 枚举类型设置为 int 数组