首页 > 解决方案 > 如何从列表中收集范围?

问题描述

所以我很难想出一种从一个列表中获取不同范围的方法。代码如下:

data = [101, 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 115, 116, 117, 118, 119, 121]
f_range = []

需求的输出print()类似于:

101-106, 108-112, 115-119, 121

我需要将这些按顺序递增的顺序分组。

标签: pythonpython-3.xlistrange

解决方案


尝试这个:

min = sorted(data)[0]
max = 0
step = 1  # Increment between each consecutive number
for c, item in enumerate(sorted(data)):
    try:
        if item + step != sorted(data)[c + 1]:
            max = item
            print (str(min) + "-" + str(max))
            min = sorted(data)[c + 1]
    except IndexError:
        max = item
        print (str(min) + "-" + str(max))
        break

希望这可以帮助。


推荐阅读