简体   繁体   English

Python3 - 在if条件下使用for循环

[英]Python3 - using for loop in a if condition

I would like to do things like this with a for in a single line, can i do it or i have to use a filter? 我想用单行代码做这样的事情,我可以这样做,还是我必须使用过滤器?

not 0 <= n <= 255 for n in [-1, 256, 23]
# True
0 <= n <= 255 for n in [0, 255, 256]
# False
0 <= n <= 255 for n in [0, 24, 255]
# True

What you are looking for is all : 你所寻找的是all

all(0 <= n <= 255 for n in [0, 255, 256])
# False
all(0 <= n <= 255 for n in [0, 24, 255])
# True
not all(0 <= n <= 255 for n in [-1, 256, 23])
# True

I like doing such all-in-range checks like this: 我喜欢像这样做这样的全范围检查:

0 <= min(nums) <= max(nums) <= 255

That's usually faster. 那通常更快。

Measuring a little: 测量一点:

>>> from timeit import timeit
>>> timeit('0 <= min(nums) <= max(nums) <= 255', 'nums = range(256)')
10.911965313750706
>>> timeit('all(0 <= n <= 255 for n in nums)', 'nums = range(256)')
23.402136341237693
func = lambda n: 0 <= n <= 255

print(not all(map(func, [-1, 256, 23])))
# True
print(all(map(func, [0, 255, 256])))
# False
print(all(map(func, [0, 24, 255])))
# True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM