python - 在嵌套元组中寻找值

标签 python

假设我有:

t = (
    ('dog', 'Dog'),
    ('cat', 'Cat'),
    ('fish', 'Fish'),
)

而且我需要检查值是否在嵌套元组的第一位(即小写位)中。我怎样才能做到这一点?大写值并不重要,我只想搜索小写值的字符串。

if 'fish' in t:
    print "Fish in t."

不起作用。

有没有一种不用 if 语句进行 for 循环的好方法?

最佳答案

可以通过指定索引来提取元组的元素:('a', 'b')[0] == 'a'。您可以使用 list comprehension遍历某些可迭代 的所有元素。元组也是可迭代的。最后,any()告知给定可迭代对象中的任何元素是否计算为 True。将所有这些放在一起:

>>> t = (
...     ('dog', 'Dog'),
...     ('cat', 'Cat'),
...     ('fish', 'Fish'),
... )
>>> def contains(w, t):
...     return any(w == e[0] for e in t)
... 
>>> contains('fish', t)
True
>>> contains('dish', t)
False

关于python - 在嵌套元组中寻找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1144178/

相关文章:

python - Scrapy 没有在 Mac 上正确安装?

python - 错误 : too many values to unpack

python - 您如何为 Bigtable/Datastore (GAE) 设计数据模型?

python - KNeighborsClassifier 中 k 的值

python - 如何将不同的数据帧写入 csv 文件的单独工作表中?

python - 在多索引数据帧中使用 "forward-fill"有效地重新索引一个级别

python - 无法使用 Linux Alpine docker 为 AWS lambda 构建 zip 文件

python - 我尝试在 tensorflow 数据管道上使用 albumentations 时出错

python - 关于 Pandas 数据框

python - 简单的 RTMP Python 客户端