【问题标题】:How to gather ranges from a list? [duplicate]如何从列表中收集范围? [复制]
【发布时间】:2018-12-08 00:56:13
【问题描述】:

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

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

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

【问题讨论】:

  • 108-112吗?
  • 是的,抱歉,我会解决的
  • 您可能应该明确说明您要做什么,而不是让我们从输入-输出关系中弄清楚。您似乎想将顺序增加的值组合在一起,以便序列中的间隙会创建一个新组。
  • @Patrick:在我看来已经足够成为一个骗子了——我会自己投票关闭它,但我无法更改我已经输入的“太宽泛”的投票。

标签: python python-3.x list range


【解决方案1】:

试试这个:

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

希望这会有所帮助。

【讨论】:

  • 这非常有效。
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 2021-10-26
  • 1970-01-01
  • 2010-11-27
  • 2014-10-06
  • 2016-12-08
相关资源
最近更新 更多