网络编程
位置:首页>> 网络编程>> Python编程>> python判断列表的连续数字范围并分块的方法

python判断列表的连续数字范围并分块的方法

作者:shannon-Li  发布时间:2021-01-18 12:04:19 

标签:python,数字,范围,分块

情况一:列表中的数字是连续数字(从小到大)


from itertools import groupby

lst = [1, 2, 3, 5, 6, 7, 8, 11, 12, 13, 19]  # 连续数字

fun = lambda x: x[1]-x[0]
for k, g in groupby(enumerate(lst), fun):
 l1 = [j for i, j in g]  # 连续数字的列表
 if len(l1) > 1:
   scop = str(min(l1)) + '-' + str(max(l1))  # 将连续数字范围用"-"连接
 else:
   scop = l1[0]
 print("连续数字范围:{}".format(scop))

情况二:列表中的数字是非连续数字,需将列表中的数据排序


# 冒泡排序(从小到大)
lst = [4, 2, 1, 5, 6, 7, 8, 11, 12, 13, 19]

for i in range(len(lst)):
 j = i+1
 for j in range(len(lst)):
   if lst[i] < lst[j]:
     x = lst[i]
     lst[i] = lst[j]
     lst[j] = x
print("排序后列表:{}".format(lst))

来源:https://blog.csdn.net/weixin_42555131/article/details/82020064

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com