Python:检查列表是否是顺序的 [英] Python: Check whether list is sequential or not

查看:361
本文介绍了Python:检查列表是否是顺序的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要一个函数/语句来检查 mylist 的所有值是否是连续的,即十六进制列表。
例如:

$ $ $ $ $ $ $ $ $ $ def $ $ $ $ $ def defmylist(mylist)
#code返回True或False


mylist1 = ['03','04','05','06','07','08','09','0a','0b','0c '','0d','0e','0f']
mylist2 = ['03','05','06','07','08','09','0a',' 0b','0c','0d','0e','0f']

checkmylist(mylist1)
#expected to return pass
checkmylist(mylist2)
#expected返回失败


解决方案

  def checkmylist(mylist):
it =(int(x,16)for m in mylist)
first = next(it)
return all(a == b对于a,b在枚举(它,第一+ 1))

十六进制数字给一个整数生成器。用 next(it)我们取出生成器的第一个元素。然后我们枚举从 first + 1 开始编号的其余元素。我们得出结论:如果每个元素的编号与元素本身的编号相同,我们有一个顺序列表。


Want a function / statement, to check whether all the values of mylist are sequential or not, which is hexadecimal list. For example:

def checkmylist(mylist):
    #code returns True or False


mylist1 = ['03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c','0d', '0e', '0f']
mylist2 = ['03', '05', '06', '07', '08', '09', '0a', '0b', '0c','0d', '0e', '0f']

checkmylist(mylist1)
#expected to returns pass
checkmylist(mylist2)
#expected to returns fail

解决方案

def checkmylist(mylist):
    it = (int(x, 16) for x in mylist)
    first = next(it)
    return all(a == b for a, b in enumerate(it, first + 1))

With the first statement we convert the hex numbers to a generator of integers. With next(it) we take the first element of the generator. Then we enumerate the rest of the elements starting the numbering from first + 1. We conclude that we have a sequential list if the numbering of each element is the same as the element itself.

这篇关于Python:检查列表是否是顺序的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆