检查十六进制值列表是否是连续的

2022-01-24 00:00:00 python list iteration sequence hex

问题描述

想要一个函数/语句,检查mylist的所有值是否是连续的,即hexadecimal列表.例如:

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

在第一条语句中,我们将十六进制数转换为整数生成器.使用 next(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.

相关文章