Check for the existence of a string in a list of t

2020-08-02 19: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