简体   繁体   中英

how to get first element of tuples with matching second element (python)

how to get first element of tuples with matching second element the expected behavior is

('John','P')
('Mary','P') 
getAll('P') 

which returns ['John','Mary']

Use a list comprehension:

>>> lis = [ ('John','P'), ('Mary','P') ]
def getall(my_list, s):
    return [x for x, y in my_list if y==s]
... 
>>> getall(lis, 'P')
['John', 'Mary']

If you're doing this multiple times then it's better to use a dictionary here:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for v, k in lis:
...     d[k].append(v)
...     
>>> d['P']
['John', 'Mary']

The following function allows you to filter as desired:

data = [('John','P'), ('Mary','P')]

def getAll(mydata, key):
    return [item[0] for item in mydata if item[1] == key]

This uses a list comprehension that includes the first element of the tuple but only when the second element of the tuple matches key (in your example 'P' ).

Assuming you have a list of these tuples? This answer doesn't use a list comprehension, for simplicity. If you're asking this question, you probably don't know what a list comprehension is.

def get_all(foo, that_list):
    new_list = []
    for item in that_list:
        if item[1] == foo:
            new_list.append(item[0])
    return new_list

some_list = [('John', 'P'), ('Mary', 'P')]
get_all('P', some_list)
[t[0] for t in list_of_tuples if t[1] == 'P']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM