Python - 检查一个列表中是否包含所有n个数字

4

我想检查我的列表是否包含了从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!

4个回答

5

不需要使用多个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

这个不起作用...我想要检查是否所有的数字从0到n都出现了,其中n是列表中的最大数。例如 - 如果列表中的最大数是5,则无论顺序如何,0、1、2、3、4、5都应该存在。 - ProgrammingNoob
@FallenAngel 为什么?你说的是“从0到列表中最大的数字”,这就是你想要的。 - Mazdak
虽然原问题中没有提到,但我担心这个解决方案不会起作用,如果原列表具有重复项并且元素数比比较列表多。例如。 l = [0,1,2,4,5,6,8,2,7,2,4,5](不包含3和2,4,5是重复的)。但同意,原问题中没有提到两个列表是否具有相同的大小。 - gabhijit
@gabhijit 这是另一种情况,可以通过set来解决。 - Mazdak

1

缓慢而低效的解决方案:

def f(myList):
    ll = [i for i in range(max(myList))] 
    diff = set(ll).difference(set(myList))
    if diff: return (False, diff)
    return (True, "sequence without blanks")

#lets test:
t1,t2 = [0,1,7,4,5,2],[3,5,4,2,1,0]
print(map(f,(t1,t2)))

1

像往常一样-这里的集合是我最喜欢的-

原始列表

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

另一个比较列表。
l2 = range(8)

# intersection of two sets is the set of compare list. 
# This solution would work when the size of original list is different than size of the compare list
set(l) & set(l2) == set(l2) 

0

你可以尝试测试集:

len(set(l))==max(l)+1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接