Home > Enterprise >  Compare two nested lists in Python
Compare two nested lists in Python

Time:10-28

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:

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.

CodePudding user response:

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]]
]
  • Related