python - 测试列表中的连续数字

标签 python list python-3.x

我有一个只包含整数的列表,我想检查列表中的所有数字是否连续(数字的顺序无关紧要)。

如果有重复的元素,函数应该返回 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/

相关文章:

python - sympy 符号矩阵平方根

python - 为什么 jupyter 显示 "None not found"?

java - 对象无法转换为整数错误

python - 在 2D 计划中放置 N 个代理

python - 这个 pandas dataframe.apply(lambda) 有什么问题?

Python/解析 : BeautifulSoup error "module obj is not callable" with results from Mechanize

c - 我有一个程序无法在 Ubuntu 上运行,但可以在 Windows 上运行

c# - WPF/C# 将自定义对象列表数据绑定(bind)到 ListBox?

python - Tornado: initialize() 和 prepare() 之间的区别

performance - 典型的二维数组路径查找的最快方法是什么?