在Python中,要检查一个元素是否存在于两个列表中,我们可以使用以下代码:
if elem in list1 and elem in list2:
我们能为这个目的做以下事情吗?
if elem in (list1 and list2):
不行。
list1 and list2
的意思是“如果 list1
为空,则为 list2
,否则为 list1
”,所以这并不能检查你想要检查的内容。
可以在交互式解释器中尝试一下。
实现这个功能的简单方法就是你已经有的代码:
if elem in list1 and elem in list2:
它起作用,易于阅读,并且编写明显。如果有一种明显的方法可以做某事,Python通常会避免添加不添加任何好处的同义词。(“TOOWTDI”或“There should be one--and preferably only one--obvious way to do it.”)
如果您正在寻找一个在某个特定方面更好的答案,而不仅仅是不同的,那么根据您想要的内容有不同的选项。
例如,如果您经常要进行此检查:
elems_in_both_lists = set(list1) & set(list2)
现在你可以这样做:
if elem in elems_in_both_lists:
这更简单,而且速度更快。
if elem in (list1 and list2):
这并不适用于指定目的。Python解释器首先检查list1,如果发现为空(即 False
),它只返回空列表(为什么?- False
和任何东西都会始终导致false,所以为什么要进一步检查?)如果不为空(即评估为True
),则返回list2
(为什么?- 如果第一个值是True
,则表达式的结果取决于第二个值,如果是False
,则表达式评估为False
,否则为True
),因此上述代码变成了if elem in list1
或if elem in list2
,具体取决于您的实现。这被称为短路。
Wiki关于短路的页面可能会有所帮助。
例子-
>>> list1 = [1, 2]
>>> list2 = [3, 4]
>>> list1 and list2
[3, 4]
>>> list1 = []
>>> list2 = [3, 4]
>>> list1 and list2
[]
list1 and list2
将返回第一个空列表(因为空列表被视为假值),或者如果所有列表都非空,则使用最右边的列表。>>> [1] and [1,2,3]
[1, 2, 3]
>>> [1,2] and []
[]
>>> [] and []
[]
>>> [] and [1,2]
[]
>>> [1] and [] and [1,2]
[]
list1 and list2
并不会返回布尔值,它将返回list1
或list2
。当然,使用bool(…)
会返回布尔值,但这与in
的操作无关。 - abarnertlist1 和 list2
吗? - Sukrit Kalra不行,但你可以这样写:
{elem}.intersection (list1, list2)
可以在这里使用all()函数:
list1 = [1, 2, 3]
list2 = [2, 4, 6]
if all(elem in list for list in [list1, list2]):
print("elem appears in both list1 and list2")
all(2 in i for i in zip([2,3], [2,4]))
。 - DSMall(2 in i for i in zip([1,2],[0,1,2]))
。你的代码翻译为 对于从list1和list2中的每个相应的对(最多到较短的列表),每个对中都有元素吗?
。另一方面,all(elem in i for i in (list1, list2))
可以工作。 - DSMany
。发现得好。 - abarnert针对此代码示例,布尔运算符and
将返回测试的值之一(真值测试),因此您将仅针对其中一个进行测试,这并不能保证正确的结果。
>>> elem = 1
>>> list1 = [2, 3, 0]
>>> list2 = [1, 2, 3]
>>> if elem in (list1 and list2):
... print "IN"
...
>>> IN
我不确定 * 何时成为一种事物,但它允许 'in' 与嵌套列表一起使用
Lists = {
'List 1': [
'11',
'12',
'13',
'14'
],
'List 2': [
'21',
'22',
'23',
'24'
]
}
if '22' in [*Lists['List 1'],*Lists['List 2']]:
print('found')
else:
print('not found')
if all([element in l for l in [list1, list2]]):
...我刚刚找到了一种方法来扩展它,以便检查每个列表中是否有多个元素:
if all([all([x in l for x in [elem1, elem2]]) for l in [list1, list2]]):
我猜如果只有2个列表和2个元素,你可能更愿意像第一个那样做(只需在中间写and
),但如果有一天你需要检查10个元素是否在4个列表中,这可能会派上用场。
(list1 and list2)
会计算布尔运算并返回最后一个列表 - 如果两个列表都有元素,则返回list2
。
所以,不,那样行不通。
list1 = [1, 2, 3]
list2 = [2, 4, 5]
list1 and list2
返回 [2, 4, 5]
list2 and list1
返回 [1, 2, 3]
if 1 in (list1 and list2):
print "YES"
else:
print "NO"
不会给
if 1 in (list2 and list1):
print "YES"
else:
print "NO"
将会返回 "YES"