Search for an item in lists and display the subscription item
I am having a problem finding a specific value within sublist and only displaying the desired sublist in my list.
The code will help you understand my problem:
list1 = [['12', '"id1"', '1'],['14', '"id1"', '1'],['16', '"id1"', '1']]
list2 = [['4', '"id8"', '1'],['6', '"id8"', '1'],['12', '"id8"', '1']]
list1_first = [int(item[0]) for item in list1]
list2_first = [int(item[0]) for item in list2]
compare = set(list1_first) & set(list2_first)
print(list1_first) # outputs: [12, 14, 16]
print(list2_first) # outputs: [4, 6, 12]
print(compare) # outputs: {12}
# find the compared value within list 1 and list 2
largelist = list1 + list2
print(largelist) # outputs: [['12', '"id1"', '1'], ['14', '"id1"', '1'], ['16', '"id1"', '1'], ['4', '"id8"', '1'], ['6', '"id8"', '1'], ['12', '"id8"', '1']]
for item in largelist:
if compare in list1:
print('Found:',item) # does not print anything
# wanted output: Found: ['12', '"id1"', '1'], Found ['12', '"id8"', '1']
My code doesn't print anything and I think this is based on the fact that the first number in each list was not annotated as an integer? Do you know why it doesn't work and how can I fix it?
source to share
You are comparing the set {12}
for each subscription in list1
, you need to see if there is any item from each subnet in the set.
Not really sure what you want, but this might be closer:
list1 = [['12', '"id1"', '1'],['14', '"id1"', '1'],['16', '"id1"',
list1_first = [(item[0]) for item in list1]
compare = set(list1_first).intersection(ele[0] for ele in list2)
from itertools import chain
for item in chain(list1,list2):
if compare.issubset(item):
print('Found:',item)
What are the outputs:
Found: ['12', '"id1"', '1']
Found: ['12', '"id8"', '1']
You can hash a string, so it's completely pointless casting for an int.
You can also use dict and filter to iterate through the lists:
list1 = [['12', '"id1"', '1'],['14', '"id1"', '1'],['16', '"id1"', '1']]
list2 = [['4', '"id8"', '1'],['6', '"id8"', '1'],['12', '"id8"', '1']]
from itertools import chain
from collections import defaultdict
d = defaultdict(list)
for item in chain(list1,list2):
d[item[0]].append(item)
print(list(filter(lambda x: len(x)> 1, d.values())))
source to share