通过字符串和python中的列表工作[重复]

时间:2022-05-09 20:44:04

This question already has an answer here:

这个问题在这里已有答案:

I have 5 set of lists and some of strings in those lists are repetitive

我有5组列表,这些列表中的一些字符串是重复的

now! I wanna know the number of repetition! for example the word "A" is in all of my lists by "B" is just in "3" or "C" is in 4 of them.

现在!我想知道重复的次数!例如,单词“A”在我的所有列表中,“B”只是在“3”或“C”在其中4。

How can I sort this problem, by using remove() I faced to wrong answer

我如何通过使用remove()来解决这个问题,我遇到了错误的答案

Thank you in advance!

先谢谢你!

1 个解决方案

#1


-2  

Take a look at Counter

看看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})

The above will get you counts of each but it seems like you're more concerned at a list level.

以上内容将为您提供各自的计数,但似乎您更关注列表级别。

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})

#1


-2  

Take a look at Counter

看看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})

The above will get you counts of each but it seems like you're more concerned at a list level.

以上内容将为您提供各自的计数,但似乎您更关注列表级别。

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})

相关文章