按字符串工作并在 python 中列出
work by strings and list in python
我有 5 组列表,这些列表中的一些字符串是重复的
现在!我想知道重复的次数!例如,"A" 这个词在我所有的列表中,"B" 只在“3”中,或者 "C" 在其中的 4 个中。
如何解决这个问题,使用 remove() 我遇到了错误的答案
提前致谢!
看看Counter
from collections import Counter
a = ['a','a','b','b']
b = ['b','b','c','d']
c = a+b
cnt = Counter()
for x in c:
cnt[x] +=1
print(cnt)
Counter({'a': 2, 'b': 4, 'c': 1, 'd': 1})
以上将为您提供每一项的计数,但您似乎更关心列表级别。
from collections import defaultdict
f = defaultdict(list)
a = ['a','a','b','b']
b = ['b','b','c','d']
c = ['e','f','g','h']
d = a + b + c
for i in d:
f[i] = 0
if i in b:
f[i] += 1
if i in c:
f[i] +=1
if i in a:
f[i] +=1
print (f)
defaultdict(list,
{'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1})
我有 5 组列表,这些列表中的一些字符串是重复的
现在!我想知道重复的次数!例如,"A" 这个词在我所有的列表中,"B" 只在“3”中,或者 "C" 在其中的 4 个中。
如何解决这个问题,使用 remove() 我遇到了错误的答案
提前致谢!
看看Counter
from collections import Counter
a = ['a','a','b','b']
b = ['b','b','c','d']
c = a+b
cnt = Counter()
for x in c:
cnt[x] +=1
print(cnt)
Counter({'a': 2, 'b': 4, 'c': 1, 'd': 1})
以上将为您提供每一项的计数,但您似乎更关心列表级别。
from collections import defaultdict
f = defaultdict(list)
a = ['a','a','b','b']
b = ['b','b','c','d']
c = ['e','f','g','h']
d = a + b + c
for i in d:
f[i] = 0
if i in b:
f[i] += 1
if i in c:
f[i] +=1
if i in a:
f[i] +=1
print (f)
defaultdict(list,
{'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1})