Python-检查元素是否同时在两个列表中 [英] Python - checking if an element is in two lists at the same time

查看:200
本文介绍了Python-检查元素是否同时在两个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,要检查一个元素是否在两个列表中,我们这样做

In Python, to check if an element is in two lists, we do

if elem in list1 and elem in list2:

我们可以为此目的执行以下操作吗?

Can we do the following for this purpose?

if elem in (list1 and list2):

推荐答案

不,您不能.

list1和list2 的意思是" list1 为空,否则为 list2 ".因此,这不会检查您要检查的内容.

list1 and list2 means "list1 if it's empty, list2 otherwise". So, this will not check what you're trying to check.

在交互式解释器中尝试一下,看看.

Try it in the interactive interpreter and see.

执行此操作的简单方法是您已经拥有的代码:

The simple way to do this is the code you already have:

if elem in list1 and elem in list2:

它有效,易于阅读,而且很明显可以编写.如果有一种明显的方法可以做某事,Python通常会尝试避免添加不会带来任何好处的同义词.("TOOWTDI"或应该有一种-最好只有一种-显而易见的方式.")

It works, it's easy to read, and it's obvious to write. If there's an obvious way to do something, Python generally tries to avoid adding synonyms that don't add any benefit. ("TOOWTDI", or "There should be one-- and preferably only one --obvious way to do it.")

如果您以某种特定方式寻找更好的答案,而不仅仅是不同,则根据您的需求提供不同的选择.

If you're looking for an answer that's better in some particular way, instead of just different, there are different options depending on what you want.

例如,如果您要经常进行此检查:

For example, if you're going to be doing this check often:

elems_in_both_lists = set(list1) & set(list2)

现在您可以这样做:

if elem in elems_in_both_lists:

这更简单,也更快.

这篇关于Python-检查元素是否同时在两个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆