在 Python 中检查元素是否存在于元组的元组中
pythonserver side programmingprogramming更新于 2025/12/25 23:08:17
Python 元组可以嵌套。我们可以有一个元组,其元素也是元组。在本文中,我们将了解如何找出给定值是否作为元素存在于元组的元组中。
使用 any
any 函数可用于在 for 循环的帮助下检查给定值是否作为元素存在于元组中存在的任何子元组中。我们将检查的整个条件放在 if 和 else 子句中。
示例
Atuple = [('Mon',10),('Tue',8),('Wed',8),('Thu',5)]
# 给定元组
print("Given tuple: ",Atuple)
# 使用 any
if any('Tue' in i for i in Atuple):
print("present")
else :
print("Not present")
if any(3 in i for i in Atuple):
print("present")
else :
print("Not present")
输出
运行上述代码得到以下结果 −
Given tuple: [('Mon', 10), ('Tue', 8), ('Wed', 8), ('Thu', 5)]
present
Not present
使用 itertools.chain
itertools 模块中的 chain 函数返回第一个可迭代对象的元素,直到用尽为止,然后继续到下一个可迭代对象,直到用尽所有可迭代对象。因此,我们将它与给定的元组一起使用,展开其所有内容,并使用 if 子句检查是否存在所需值。
示例
import itertools
Atuple = (('Mon',10),('Tue',8),('Wed',8),('Thu',5))
#给定元组
print("Given tuple: ",Atuple)
# 使用 chain
if ('Wed' in itertools.chain(*Atuple)) :
print("Wed is present")
else :
print("Wed is not present")
if (11 in itertools.chain(*Atuple)) :
print("11 is present")
else :
print("11 is not present")
输出
运行上述代码得到以下结果 −
Given tuple: (('Mon', 10), ('Tue', 8), ('Wed', 8), ('Thu', 5))
Wed is present
11 is not present
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

