Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare two nested lists in Python

I have two lists:

list_a = [["the", "ball", "is", "red", "and", "the", "car", "is", "red"],
          ["the", "boy", "is", "tall", "and", "the", "man", "is", "tall"]]
list_b = [["the", 0], ["ball", 0], ["is", 0], ["red", 0], ["and", 0], ["car", 0]],
          ["The", 0], ["boy", 0], ["is", 0], ["and", 0], ["man", 0], ["tall", 0]]          

Goals:

Iterate over list_b, pick up the specific string and check if it is in list_a and if so, increase the specific int by 1.
Important in that context is that I will only compare list_a[0] with list_b[0] and list_a[1] with list_b[1].
When finished it should look like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list_a = [["the", "ball", "is", "red", "and", "the", "car", "is", "red"],
          ["the", "boy", "is", "tall", "and", "the", "man", "is", "tall"]]
list_b = [["the", 2], ["ball", 1], ["is", 2], ["red", 2], ["and", 1], ["car", 1]],
          ["the", 2], ["boy", 1], ["is", 2], ["and", 1], ["man", 1], ["tall", 2]]

for loops give me massive problems and it seems that this approach is wrong and not suitable for this task, so I am open and thankful for different solutions.

>Solution :

You can use enumerate and find the index of each row in list_b and base row_index, Use collections.Counter for list_a and update value in each sublist of each row in list_b.

from collections import Counter

for row, lst_b in enumerate(list_b):
    cnt_list_a = Counter(list_a[row])
    for lst in lst_b:
        lst[1] = cnt_list_a[lst[0].lower()]
    
print(list_b)

Output:

[
    [['the', 2], ['ball', 1], ['is', 2], ['red', 2], ['and', 1], ['car', 1]], 
    [['The', 2], ['boy', 1], ['is', 2], ['and', 1], ['man', 1], ['tall', 2]]
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading