lst = ["dog cat mouse", " cat mouse", "mouse mouse cat"]
res = {}
res2 = []
for i in lst:
for j in i.split(' '):
if j not in res.keys():
res[j] = 1
else:
res[j] += 1
for i in lst:
res2.append('+'.join([str(res[j]) for j in i.split(' ')]))
print(res2)
from collections import Counter
strings = ["dog cat mouse", " cat mouse", "mouse mouse cat"]
words_lists = [string.split() for string in strings]
counts = Counter([word for lst in words_lists for word in lst])
result = [sum(counts[word] for word in lst) for lst in words_lists]
计数器列表的项目只能以字符串的形式存储,之后可以使用
eval()
对字符串进行求值代码:
结果(
res2
)应该类似于['1+3+4', '3+4', '4+4+3']
我想这就是你想要的
另一项提案
Counter
:结果:
相关问题 更多 >
编程相关推荐