特定对象的Python计数排除
我有以下问题,如果能得到一些帮助,我将不胜感激特定对象的Python计数排除,python,list,tuples,Python,List,Tuples,我有以下问题,如果能得到一些帮助,我将不胜感激 a =[['911', 'strength', 'Bolero lists 12 pounds hassle free and stress free.'], ['912', 'power', 'Bolero lifts free weights.']] b = ['free', 'Bolero', 'pounds'] 我要做的是把a中b的点击数加到a中。请参阅下面的代码: c = [] for sent in a: o = 0
a =[['911', 'strength', 'Bolero lists 12 pounds hassle free and stress free.'], ['912', 'power', 'Bolero lifts free weights.']]
b = ['free', 'Bolero', 'pounds']
我要做的是把a中b的点击数加到a中。请参阅下面的代码:
c = []
for sent in a:
o = 0
for i in sent:
o +=sum(i.count(col) for col in b)
c.append((sent, o))
结果是:
c =[(['911', 'strength', 'Bolero lists 12 pounds hassle free and stress free.'], 4), (['912', 'power', 'Bolero lifts free weights.'], 2)]
棘手的事情是试图将“无麻烦”从列表b中的“免费”计数中排除
因此,本质上,结果集是:
c =[(['911', 'strength', 'Bolero lists 12 pounds hassle free and stress free.'], 3), (['912', 'power', 'Bolero lifts free weights.'], 2)]
谢谢。如果要删除
“无麻烦”
请从a
中的每个字符串中计数。您可以在for
循环中减去它:
for sent in a:
o = 0
for i in sent:
o += sum(i.count(col) for col in b)
o -= i.count("hassle free")
c.append((sent, o))
输出:
[(['911', 'strength', 'Bolero lists 12 pounds hassle free and stress free.'], 3), (['912', 'power', 'Bolero lifts free weights.'], 2)]
如果只想对
b
中的每个项目进行一次计数,可以执行以下操作:
for sent in a:
o = 0
for word in b: # loop over b, so each item counted only once
for s in sent: # work through sentence
if word in s:
o += 1
break # add one only
c.append((sent, o))
可以使用列表缩短:
c = [(sent, sum(any(word in s for s in sent) for word in b)) for sent in a]
为什么在第二个屏幕上出现1
?为什么要排除“无麻烦”?你想每个单词只匹配一次吗?谢谢你指出这一点。这是一个打字错误。从总和中减去i.count(“无麻烦”)
o+=sum(b列的i.count(col))i.count(“无麻烦”)
非常感谢您!好的,克里斯蒂安,你的方式开启了很多可能性。我知道这对你来说很琐碎,但这绝对有帮助。我现在可以在排除列表中添加更多短语。谢谢你,谢谢你,乔恩!这很有帮助。