如果列表只包含0s,我如何在python中打印?
list1=[0,0,0,0,0,0]
if list1 has all 0s
print("something")
我希望输出是“东西”
解决方法:
if all(item == 0 for item in list1):
print("something")
演示:
>>> list1 = [0,0,0,0,0,0]
>>> all(item == 0 for item in list1)
True
另一种选择是使用集合,如果列表中的所有项目都是可清除的:
>>> set(list1) == {0}
True
但是,这将在内存中创建一组,它不会短路像所有的(),所以这将是内存低效和缓慢的平均情况.
>>> 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
标签:python,list