Check for the existence of a string in a list of tuples by specific index

久未见 提交于 2020-06-11 13:11:27

问题


If I have:

my_list = [('foo', 'bar'), ('floo', 'blar')]

how can I easily test if some string is in the first element in any of those tuples?

something like:

if 'foo' in my_list

where we are just checking the first element of each tuple in the list?


回答1:


If you want to check only against the first item in each tuple:

if 'foo' in (item[0] for item in my_list)

Alternatively:

if any('foo' == item[0] for item in my_list)



回答2:


You can first extract a list of only the first items and then perform a check:

>>> my_list = [('foo', 'bar'), ('floo', 'blar')]
>>> 'foo' in list(zip(*my_list))[0]
True

Alternatively:

>>> 'foo' in next(zip(*my_list))
True



回答3:


Use the batteries:

import operator

if 'foo' in map(operator.itemgetter(0), my_list):

This won't create a copy of your list and should be the fastest.




回答4:


if 'foo' in map(lambda x: x[0], my_list):
    <do something>

map takes each element in the list, applies a function to it, and returns a list of the results. In this case, the function is a lambda function that just returns the first sub element of the original element.

((0,1),(3,4)) becomes (0,3).




回答5:


my_list = iter(my_list)

result = False

while True:
    try:
        x, y = my_list.next()
        if x == 'foo':
            result = True
            break
    except StopIteration:
        break


来源:https://stackoverflow.com/questions/9319240/check-for-the-existence-of-a-string-in-a-list-of-tuples-by-specific-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!