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

yipeiwu_com6年前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中字典(dict)和列表(list)的排序方法实例

一、对列表(list)进行排序 推荐的排序方式是使用内建的sort()方法,速度最快而且属于稳定排序复制代码 代码如下:>>> a = [1,9,3,7,2,0,5]&...

pyqt5实现绘制ui,列表窗口,滚动窗口显示图片的方法

pyqt5实现绘制ui,列表窗口,滚动窗口显示图片的方法

1:listWidget 以滚动窗口显示文件下的所有文件: self.listWidget = QtWidgets.QListWidget(self.gridLayout...

wxPython电子表格功能wx.grid实例教程

本文实例为大家分享了wxPython电子表格功能的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python #encoding: utf8 import wx...

python中print()函数的“,”与java中System.out.print()函数中的“+”功能详解

python中的print()函数和java中的System.out.print()函数都有着打印字符串的功能。 python中: print("hello,world!") 输出...

Python常见加密模块用法分析【MD5,sha,crypt模块】

本文实例讲述了Python常见加密模块用法。分享给大家供大家参考,具体如下: 1. md5模块 md5.new([arg])     返回一个md...