如何检查以下项目之一是否在列表中? [英] How to check if one of the following items is in a list?

查看:38
本文介绍了如何检查以下项目之一是否在列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种简短的方法来查看以下任何项目是否在列表中,但我的第一次尝试不起作用.除了编写一个函数来实现这一点之外,还有一种简单的方法来检查多个项目中的一个是否在列表中.

<预><代码>>>>a = [2,3,4]>>>打印(1 或 2)在一个错误的>>>打印(2 或 1)在一个真的

解决方案

>>>L1 = [2,3,4]>>>L2 = [1,2]>>>[i for i in L1 if i in L2][2]>>>S1 = 设置(L1)>>>S2 = 设置(L2)>>>S1.交叉口(S2)设置([2])

空列表和空集都是 False,所以你可以直接使用该值作为真值.

I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.

>>> a = [2,3,4]
>>> print (1 or 2) in a
False
>>> print (2 or 1) in a
True

解决方案

>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]


>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])

Both empty lists and empty sets are False, so you can use the value directly as a truth value.

这篇关于如何检查以下项目之一是否在列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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