简体   繁体   中英

How to search tuple with three elements inside list

I have a list as below

tlist=[(‘abc’,HYD,’user1’), (‘xyz’,’SNG’,’user2’), (‘pppp’,’US’,’user3’), (‘qq’,’HK’,’user4’)]

I want to display the second field tuple of provided first field of tuple.

Ex:
tlist(‘xyz’) 
SNG

Is there way to get it?

A tuple doesn't have a hash table lookup like a dictionary, so you will need to loop through it in sequence until you find it:

def find_in_tuple(tlist, search_term):
    for x, y, z in tlist:
        if x == search_term:
            return y

print(find_in_tuple(tlist, 'xyz')) # prints 'SNG'

If you plan to do this multiple times, you definitely want to convert to a dictionary. I would recommend making the first element of the tuple the key and then the other two the values for that key. You can do this very easily using a dictionary comprehension.

>>> tlist_dict = { k: (x, y) for k, x, y in tlist } # Python 3: { k: v for k, *v in tlist }
>>> tlist_dict
{'qq': ['HK', 'user4'], 'xyz': ['SNG', 'user2'], 'abc': ['HYD', 'user1'], 'pppp': ['US', 'user3']}

You can then select the second element as follows:

>>> tlist_dict['xyz'][0]
'SNG'

If there would be multiple tuples with xyz as a first item, use the following simple approach(with modified example):

tlist = [('abc','HYD','user1'), ('xyz','SNG','user2'), ('pppp','US','user3'), ('xyz','HK','user4')]
second_fields = [f[1] for f in tlist if f[0] == 'xyz']

print(second_fields)  # ['SNG', 'HK']

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