Reputation: 755
Could someone please help me troubleshoot my code. I have two lists.
A = [['2925750', ' Everything he mentioned, I could have evaluated on my own'], ['2925750', ' I do wish he could have shown us more at this point that could have set the fox apart.']]
B = ['mentioned','evaluated','fox','wish']
The goal is to append to list A the number of times any item in B is present in a sentence for A.
The result should be something like:
[(['2925750', ' Everything he mentioned, I could have evaluated on my own'], 0), (['2925750', ' I do wish he could have shown us more at this point that could have set the Equinox apart.'], 0)]
The problem is my count is zero.
Below is my code. Thank you in advance:
Y = []
##Find Matches
for sent in A:
for sent in B:
Y.append((sent, sum(sent.count(col) for col in B)))
Thank you.
Upvotes: 1
Views: 258
Reputation: 362
you used 'sent' twice.
You don't need a loop for B.
'A' is a list of lists.
My fix:
Y = []
A = [['2925750', ' Everything he mentioned, I could have evaluated on my own'], ['2925750', ' I do wish he could have shown us more at this point that could have set the fox apart.']]
B = ['mentioned','evaluated','fox','wish']
for sent in A:
o = 0
for i in sent:
o +=sum(i.count(col) for col in B)
Y.append((sent, o))
Y:
[(['2925750', ' Everything he mentioned, I could have evaluated on my own'], 2), (['2925750', ' I do wish he could have shown us more at this point that could have set the fox apart.'], 2)]
Upvotes: 2
Reputation: 11039
You can't use sent
as the iterator for both loops as it is still in scope.
Upvotes: 2
Reputation: 64318
The variable sent
in for sent in B
overshadows the variable in for sent in A
. Or, to be more exact, it assigns to the same name (same variable).
You should rename one of them.
Also, note you already iterate over B
inside sum
. In the inner loop, you probably meant to iterate over each of the lists in A
.
for lst in A:
for sent in lst:
Y.append((sent, sum(sent.count(col) for col in B)))
Upvotes: 5