简体   繁体   English

Python for循环计数器列表-计数器不起作用

[英]Python for loop counter list - counter not working

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. 目的是将A中的句子中B中的任何项目出现的次数追加到列表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. 谢谢。

The variable sent in for sent in B overshadows the variable in for sent in A . for sent in B sent for sent in B的变量for sent in Afor 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 . 另外,请注意,您已经遍历了sum B In the inner loop, you probably meant to iterate over each of the lists in A . 在内部循环中,您可能打算遍历A每个列表。

for lst in A:
  for sent in lst:
      Y.append((sent, sum(sent.count(col) for col in B)))

您不能将sent用作两个循环的迭代器,因为它仍在范围内。

  • you used 'sent' twice. 您使用了两次“发送”。

  • You don't need a loop for B. 您不需要B的循环。

  • 'A' is a list of lists. “ A”是列表的列表。

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: 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)] [([['2925750','他提到的一切,我本可以自行评估'],2),(['2925750','我希望他在这一点上能向我们展示更多可能让狐狸坐下来的东西分开。'],2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM