我有一个只包含整数的列表,我想检查列表中的所有数字是否连续(数字的顺序无关紧要)。
如果有重复的元素,函数应该返回 False。
这是我尝试解决的问题:
def isconsecutive(lst):
"""
Returns True if all numbers in lst can be ordered consecutively, and False otherwise
"""
if len(set(lst)) == len(lst) and max(lst) - min(lst) == len(lst) - 1:
return True
else:
return False
例如:
l = [-2,-3,-1,0,1,3,2,5,4]
print(isconsecutive(l))
True
这是最好的方法吗?
最佳答案
这是另一种解决方案:
def is_consecutive(l):
setl = set(l)
return len(l) == len(setl) and setl == set(range(min(l), max(l)+1))
但是,您的解决方案可能更好,因为您没有将整个范围存储在内存中。
请注意,您始终可以简化
if boolean_expression:
return True
else:
return False
通过
return boolean_expression
关于python - 测试列表中的连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40091617/