-1

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.

python_ftw
  • 45
  • 5
  • This doesnt make sense because `list_a[0]` is the entire list, `["the", "ball", "is", "red", "and", "the", "car", "is", "red"]`. Do you mean `list_a[0][0]` with `list_b[0][0]`? – Tom McLean Oct 27 '22 at 18:09
  • For loops are the correct way to do this. Show what you did as a [mre] and we can help you figure out what's wrong. – Pranav Hosangadi Oct 27 '22 at 18:10
  • And `list_b[0][5]` is "car" but `list_a[0][5]` is `the` so how do they compare? – Tom McLean Oct 27 '22 at 18:10
  • Since you want to iterate over both lists in parallel so that you have the `i`th elements of both at the same time, see https://stackoverflow.com/questions/1663807/how-do-i-iterate-through-two-lists-in-parallel – Pranav Hosangadi Oct 27 '22 at 18:13
  • It looks as if you don't need to initialize `list_b` at all. You can generate the required `list_b` starting from an empty dict. – Antony Hatchkins Oct 27 '22 at 18:17

1 Answers1

3

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]]
]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30