首页 > 解决方案 > 比较列表中的相邻变量并重新格式化输入

问题描述

inp = [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17, 20, 25,27,28,29,31]

预期输出:如果相邻变量是串联的,则用连字符填充。如果没有,请附加给定的数字。

Expected Output = [1-3,5,7-12,14,17,20,25,27-29,31]

我使用下面的代码取了一个相邻的数字。但不满足要求。

inp = [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17, 20, 25,27,28,29,31]
for x,y in zip(inp[::],inp[1::]):
    print(x,y)

标签: pythonpython-3.xlist

解决方案


您可以使用itertools.groupby

from itertools import groupby

lst = [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 17, 20, 25,27,28,29,31]

out = []
for _, g in groupby(enumerate(lst), lambda k: k[1]-k[0]):
    g = [*g]
    if len(g) == 1:
        out.append(str(g[0][1]))
    else:
        out.append('{}-{}'.format(g[0][1], g[-1][1]))

print(out)

印刷:

['1-3', '5', '7-12', '14', '17', '20', '25', '27-29', '31']

推荐阅读