Find common id between a list and a list of tuple

Viewed 122

I have a list and a list of tuple:

List:

[id1, id2, id3, id4, id5]

And a list of tuple :

[(id1, 'name1'), (id2, 'name2'), (id6, 'name6')]

I want to find common ids between above lists and make a list of names with common id:

['name1', 'name2']

Also I found this method in my searches:

set(result_product_id).intersection(result_order)

But it does not work for my issue

P.S. note that "id1 , id2 , id3 , ..." are integers and i write it this way to make it easier to ask

thx

4 Answers

You could use simple list comprehension:

lst = [1, 2, 3]
tup = [(1, 'name1'), (2, 'name2'), (6, 'name6')]

result = [el[1] for el in tup if el[0] in lst]

If you want to do with set operation:

lst = [1, 2, 3, 4, 5]
tup = [(1, 'name1'), (2, 'name2'), (6, 'name6')]

orders, product_id = dict(tup), set(lst)
print([orders[k] for k in product_id & orders.keys()])

Print:

['name1', 'name2']

And also you could get those items which are in result_orders but not in product_id:

print([orders[k] for k in orders.keys() - product_id])

print:

['name6']

You just need to traverse the list with id's and names and compare the id's with the elements of the list of id's.If these match then you can append these to the names list:

ids = [555,567,597,589]
names = [(555, 'name1'), (577, 'name2'), (567, 'name6')]
common_ids = []
for i in names:
    if(i[0] in ids):    # to comapre ids stored inside the tuple with elements in the ids list
        common_ids.append(i[1])

print(common_ids)

Output:

['name1', 'name6']

And if you are comfortable with list comprehensions you could do all of the above in just one line:

ids = [555,567,597,589]
names = [(555, 'name1'), (577, 'name2'), (567, 'name6')]
common_ids = [i[1] for i in names if (i[0] in ids)]

You could learn list comprehensions here:

Note: You could also do it with set intersection method but that would be really long and the reuslt would therefore be trivial.A list comprehension is the recommended way to solve this kind of problem.

I have found the answer:

id_list = [id1, id2, id3, id4, id5]
tuple_list = [(id1, 'name1'), (id2, 'name2'), (id6, 'name6')]


def findCommon(idList, tupList):
    commonNames = []
    commonIds = []
    
    for item in tupList:
        if item[0] in idList:
            commonNames.append(item[1])
            commonIds.append(item[0])
            
    return commonNames, commonIds
    
allCommonNames, allCommonIds = findCommon(id_list, tuple_list)
Related