Python - 检查列表中是否存在所有 n 个数字

标签 python python-3.x

我想检查我的列表是否包含从0到列表最大数的所有数字

例如,这个列表包含从 0 到 7 的所有数字:

l = [0,2,1,7,6,5,4,3] 

但是这个列表没有,因为它没有 4 -

l = [0,2,1,6,5,7,3]

我尝试使用 zip:

all(x==y+1 for x, y in zip(sorted(l[1:]), sorted(l)))

但这行不通..

例如 -

l = [0,3,2,5]

没有 1 和 4 所以它应该返回 false!

在哪里 -

l = [0,2,3,1,4,5]

具有从 0 到 5 的所有数字,因此它应该返回 true!

最佳答案

不需要使用具有多个zip功能的zip。您可以使用sorted:

if sorted(l)==list(range(max(l)+1))

例子:

>>> sorted(l)==list(range(max(l)+1))
False
>>> l= [0,2,1,7,6,5,4,3] 
>>> sorted(l)==list(range(max(l)+1))
True

关于Python - 检查列表中是否存在所有 n 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30691556/

相关文章:

python - Python 中的彭博 API : How to Get Historical Reference Data

python - 对两个均为实数的张量求和时的 NaN 结果

python - 使用循环和追加读取多个 Excel 文件

Python - 查找另一列中给定匹配字符串的列的平均值

python - Boxcar 在 python/astropy 中卷积散点图?

java - boolean 条件验证

python - Mercurial API : default-push not set from repo's . hg/hgrc

python - 从 np.datetime64 转换为浮点年份

python - 如何将多个电子邮件添加到 "imaplib"搜索条件?

python-3.x - 如何在 Tensorflow 中输出预测?