我想用单行代码执行此类操作,我可以这样做,还是必须使用过滤器?
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
答案 0 :(得分:9)
您要找的是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
答案 1 :(得分:0)
我喜欢这样的全范围检查:
0 <= min(nums) <= max(nums) <= 255
通常会更快。
稍微测量一下:
>>> 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
答案 2 :(得分:0)
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