1

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.

3 Answers 3

5

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)))
Sign up to request clarification or add additional context in comments.

Comments

2
  • 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)]

1 Comment

Worked perfectly. Thank you so much!
2

You can't use sent as the iterator for both loops as it is still in scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.