简体   繁体   中英

Returning first element of a tuple after finding the tuple according to the second value in a list of tuples

I have a list of tuples that looks something like:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

I want to return the first item of the tuple after finding said tuple according to the second value. I could do something like:

for pair in list_of_tuples:
    if pair[1] == something:
        print(pair[0])

# or

[pair[0] for pair in e1_span_sent_pairs if pair[1] == something][0]

but I'm wondering if there's a way I can do this without using a for loop. Thanks.

You can create a dict, so ot's reuseable, like so:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

d = {v: (k, v) for k, v in list_of_tuples}

print(d['a'])
print(d['c'])

Output:

(1, 'a')
(3, 'c')

If the for loop annoys you, this will result in the same dict :

d = dict(map(lambda tup: (tup[1], (tup[0], tup[1])), list_of_tuples))

If you really do not want loops (even not in the form of a simple list comprehension) you could do something like:

result = map(lambda i: i[0], filter(lambda i: i[1] == 'c', list_of_tuples))

But I'd just go with list comprehension and unpacking the two elements of the tuple:

result = [l for l ,r in list_of_tuples if r == something]

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