如何使用Python的“ in”运算符检查我的列表/元组是否包含整数0、1、2? [英] How to use Python 'in' operator to check my list/tuple contains each of the integers 0, 1, 2?

查看:208
本文介绍了如何使用Python的“ in”运算符检查我的列表/元组是否包含整数0、1、2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python in 运算符检查我的列表/元组 sltn 包含每个整数0 ,1和2?

How do I use the Python in operator to check my list/tuple sltn contains each of the integers 0, 1, and 2?

我尝试了以下操作,为什么它们都错了:

I tried the following, why are they both wrong:

# Approach 1
if ("0","1","2") in sltn:
     kwd1 = True

# Approach 2
if any(item in sltn for item in ("0", "1", "2")):
     kwd1 = True






更新:为什么我必须转换( 0, 1, 2) 放入元组(1、2、3)中?或列表 [1、2、3]


Update: why did I have to convert ("0", "1", "2") into either the tuple (1, 2, 3)? or the list [1, 2, 3]?

推荐答案

if ("0","1","2") in sltn

您正在尝试检查 sltn 列表是否包含元组( 0, 1, 2),但不是。 (它包含3个整数)

You are trying to check whether the sltn list contains the tuple ("0","1","2"), which it does not. (It contains 3 integers)

但是您可以使用#all()

sltn = [1, 2, 3] # list
tab = ("1", "2", "3") # tuple

print(all(int(el) in sltn for el in tab)) # True

这篇关于如何使用Python的“ in”运算符检查我的列表/元组是否包含整数0、1、2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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