我的功能是这样的,thanks to this answer, 这是检查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 是最后一个值,那一刻我的函数应该重新初始化计数器,这可能是有效的方法。我的函数应该对有限的值集返回true。
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
答案 0 :(得分:1)
您可以使用模数运算符处理零重启:
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)
)
答案 1 :(得分:0)
您可以使用==
运算符检查排序列表是否与原始列表相同。
# 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