如果列表只包含0,我如何在python中打印?

use*_*042 3 python list

如果列表只包含0s,我如何在python中打印?

list1=[0,0,0,0,0,0]
if list1 has all 0s
print("something")
Run Code Online (Sandbox Code Playgroud)

我希望输出是"东西"

Ash*_*ary 12

用途all():

if all(item == 0 for item in list1):
   print("something")
Run Code Online (Sandbox Code Playgroud)

演示:

>>> list1 = [0,0,0,0,0,0]
>>> all(item == 0 for item in list1)
True
Run Code Online (Sandbox Code Playgroud)

sets如果列表中的所有项目都是可清除的,则另一种方法是使用:

>>> set(list1) == {0}
True
Run Code Online (Sandbox Code Playgroud)

但这会在内存中创建一个集合并且它不会像短路一样all(),所以它在内存效率低下并且在平均情况下会变慢.

>>> list1 = [0,0,0,0,0,0]*1000 + range(1000)
>>> %timeit set(list1) == {0}
1000 loops, best of 3: 292 us per loop
>>> %timeit all(item == 0 for item in list1)
1000 loops, best of 3: 1.04 ms per loop

>>> list1 = range(1000) + [0,0,0,0,0,0]*10
>>> shuffle(list1)
>>> %timeit set(list1) == {0}
10000 loops, best of 3: 61.6 us per loop
>>> %timeit all(item == 0 for item in list1)
1000000 loops, best of 3: 1.3 us per loop
Run Code Online (Sandbox Code Playgroud)