按特定索引检查元组列表中是否存在字符串

9-b*_*its 0 python tuples list

如果我有:

my_list = [('foo', 'bar'), ('floo', 'blar')]
Run Code Online (Sandbox Code Playgroud)

如何轻松测试某个字符串是否位于任何这些元组的第一个元素中?

就像是:

if 'foo' in my_list
Run Code Online (Sandbox Code Playgroud)

我们只是检查列表中每个元组的第一个元素?

sve*_*rre 5

如果您只想检查每个元组中的第一项:

if 'foo' in (item[0] for item in my_list)
Run Code Online (Sandbox Code Playgroud)

或者:

if any('foo' == item[0] for item in my_list)
Run Code Online (Sandbox Code Playgroud)