Skip to main content
 首页 » 编程设计

Python for 循环计数器列表之计数器不工作

2025年05月04日14grandyang

有人可以帮我解决我的代码问题吗? 我有两个列表。

    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'] 

目标是将 B 中的任何项目在 A 的句子中出现的次数附加到列表 A。

结果应该是这样的:

[(['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)] 

问题是我的计数为零。

下面是我的代码。提前致谢:

Y = [] 
 
 
##Find Matches 
for sent in A: 
  for sent in B: 
      Y.append((sent, sum(sent.count(col) for col in B))) 

谢谢。

请您参考如下方法:

for sent in B 中的变量sent 掩盖了for sent in A 中的变量。或者,更准确地说,它分配给相同的名称(相同的变量)。

您应该重命名其中一个。

另外,请注意您已经在 sum 中迭代了 B。在内部循环中,您可能打算遍历 A 中的每个列表。

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