我有一个只包含整数的列表,我想检查列表中的所有数字是否连续(数字的顺序无关紧要)。测试列表中的连续数字
如果有重复的元素,该函数应该返回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
这是做到这一点的最好方法是什么?
您的示例列表不是连续的 - 它可以重新排序为连续的整数,是什么意思?我们可以重新排列名单吗? –
@DanielleM。顺序没关系 – MMF
看起来很好,但你应该删除if并只是返回整个表达式 –