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))

以上这篇python判断列表的连续数字范围并分块的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战