Test if value exists in several lists

笑着哭i 提交于 2019-12-07 07:25:13

问题


I would like to check if a value exists in every list.

The following returns True as expected, but seems un-pythonic.

What is the correct/more elegant way to do this?

a = [1 ,2]
b = [1, 3]
c = [1, 4]
d = [2, 5]

False in [True if 1 in l else False for l in [a, b, c, d]  ]

回答1:


You can use all and a generator expression:

all(1 in x for x in (a, b, c, d))

Demo:

>>> a = [1 ,2]
>>> b = [1, 3]
>>> c = [1, 4]
>>> d = [2, 5]
>>> all(1 in x for x in (a, b, c, d))
False
>>> all(1 in x for x in (a, b, c))
True
>>>

In addition to being more readable, this solution is more efficient since it uses lazy-evaluation. It will only check as many items as is necessary to determine the result.

Also, there is never a good reason to do:

True if 1 in l else False

or something similar since in already returns a boolean result. All you need is:

1 in l

For the negated version, use:

1 not in l


来源:https://stackoverflow.com/questions/27715213/test-if-value-exists-in-several-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!