简体   繁体   中英

Search lIst inside tuple - Python

Am fairly new to Python and stumped on what I think is quite straight forward, I have a list of tuples. where the second elemnt of the tuple is a list itself, What I need to do is search the second element and if anything in that list, matches another separate list. then return the first element of the tuple: Example:

tuplelist = [('Bob', ['1', '3', '5']), ('Alice', ['2', '4', '4', '6'])

list_2_check = ['1']

So in this case '1' is a match for the list in the first tuple, in which case I want to return the name 'Bob'.

I can perform the match, but no idea how to then return the first item of the tuple.

Thanks

First of all maybe list_2_check is wrong because the list contain an integer and not a string. I guess to apply a in set match operator.

This can be a starting point:

[k for k,v in tuplelist if set(list_2_check)&set(v)]
# ['Bob']

This code is inefficient, but the idea is to use set() in order to works with the correct operators. maybe the first init must be refactored in order to use the correct data type. If you have a lot of data, this way is not so fast.

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