how do i print in python if a list contains only 0s??
如果列表只包含0s,我如何在python中打印?
list1=[0,0,0,0,0,0]
if list1 has all 0s
print("something")
I want the output to be "something"
我希望输出是“东西”
3 个解决方案
#1
12
Use all()
:
使用all():
if all(item == 0 for item in list1):
print("something")
Demo:
演示:
>>> list1 = [0,0,0,0,0,0]
>>> all(item == 0 for item in list1)
True
Another alternative will be to use sets
, if all the items in list are hashable:
另一种选择是使用集合,如果列表中的所有项目都是可清除的:
>>> set(list1) == {0}
True
But this will create a set in memory and it won't short-circuit like all()
, so it is going to be memory inefficient and slow in average cases.
但是这将在内存中创建一个集合并且它不会像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
#2
2
I think a very fast way is to use [].count
我认为一种非常快速的方法是使用[] .count
L.count(0) == len(L)
if the list is HUGE and most not being zeros then all
with an iterator may be better, however.
如果列表是巨大的并且大多数不是零,则所有使用迭代器的可能更好。
#3
0
You can skip the list comprehension / generator expression by doing:
您可以通过执行以下操作跳过列表理解/生成器表达式:
if not any(list1):
#1
12
Use all()
:
使用all():
if all(item == 0 for item in list1):
print("something")
Demo:
演示:
>>> list1 = [0,0,0,0,0,0]
>>> all(item == 0 for item in list1)
True
Another alternative will be to use sets
, if all the items in list are hashable:
另一种选择是使用集合,如果列表中的所有项目都是可清除的:
>>> set(list1) == {0}
True
But this will create a set in memory and it won't short-circuit like all()
, so it is going to be memory inefficient and slow in average cases.
但是这将在内存中创建一个集合并且它不会像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
#2
2
I think a very fast way is to use [].count
我认为一种非常快速的方法是使用[] .count
L.count(0) == len(L)
if the list is HUGE and most not being zeros then all
with an iterator may be better, however.
如果列表是巨大的并且大多数不是零,则所有使用迭代器的可能更好。
#3
0
You can skip the list comprehension / generator expression by doing:
您可以通过执行以下操作跳过列表理解/生成器表达式:
if not any(list1):