Python: 检查列表是否顺序|列表末尾定义

Python: Check whether the list is in sequential or not | End of the list is defined

我的功能是这样的, 这是检查mylist的所有值是否是连续的,这是十六进制列表。例如:

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']

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


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

但是我的函数还需要一个逻辑,它应该检查列表,即使列表的最后一个值是已知的,例如,

00 to 10 | 00 to 0a(Hex)

这里已经知道 10 是最后一个值,那一刻我的函数应该重新初始化计数器,这可能是执行此操作的有效方法。对于有限的值集,我的函数应该 return 为真。

mylist = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a','00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a']

checkmylist(mylist)
#Expected True 

您可以使用 == 运算符来检查排序后的列表是否与原始列表相同。

# list is not in order
mylist = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a','00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a']

# list is in order
mylist2 = ['03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c','0d', '0e', '0f']

sorted(mylist) == mylist # returns False
sorted(mylist2) == mylist2 # returns True

您可以使用取模运算符处理从零开始的重启:

mylist = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a',
          '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a']

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

checkmylist(mylist) # returns True

对于 10 以外的已知结束值,您需要使用函数的第二个参数(例如 checkmylist(mylist, end=14)