python - 如何从列表中收集范围?
问题描述
所以我很难想出一种从一个列表中获取不同范围的方法。代码如下:
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
我需要将这些按顺序递增的顺序分组。
解决方案
尝试这个:
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
希望这可以帮助。
推荐阅读
- java - 如何分配 onGifSelected?
- r - 在函数中使用卷曲运算符时出错
- javascript - 本机 JavaScript 语法中的千位分隔符
- python - 选择特定项目时的组合框信号
- crystal-lang - centos水晶中的应用程序编译获取错误
- vim - 自动打开两个窗格
- hyperledger-fabric - 当我想实例化我的链码时出错
- sql - 如何正确创建相互引用的表?
- python - 如何编写一个Ceaser Cipher Python
- django - 如果没有定义 self.kwargs 来自哪里的问题?特别是在 django 代码库中的 SingleObjectMixin 类中