简体   繁体   中英

Finding element within lists and output the sublist item

I am having a problem containing searching a specific value within a sublist and output only the desired sublist within my list.

The code will help understanding 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 does not print anything and I think that is based on the fact that the first number in each list is not been annotated as an integer? Do you know why this not works and how could I fix it?

You are comparing a set {12} to each sublists in the list1 , you need to see if any element from each sublist is in the set.

Not fully sure what you want but this may 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)

Which outputs:

Found: ['12', '"id1"', '1']
Found: ['12', '"id8"', '1']

You can hash a string so it is completely pointless casting to an int.

You can also use a dict and filter to do one pass over 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())))

Your code does not print anything because of

if compare in list1:

compare is a set, and list1 does not contain any sets.

Your code prints all the items in largelist if {12} (the set that contains only the number 12 ) is in list1 . If you want to print the items whose number is in both of the lists, you can do it with:

for item in largelist:
    if int(item[0]) in compare:
        print('Found:', item)

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