Reputation: 287
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
Upvotes: 1
Views: 174
Reputation: 573
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)
['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:
Upvotes: 2
Reputation: 631
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)
Upvotes: 1
Reputation: 12672
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']
Upvotes: 2
Reputation: 933
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]
Upvotes: 3