计算字符串列表中的特定字符

发布于 2025-01-19 16:47:41 字数 409 浏览 0 评论 0原文

嗨,我要做的是计算下列表中每个字符串共有的字符的特定出现,并打印出每个字符串以及出现的常见字符的次数 例子 巴拉克A出现2 Barack R出现1 当我运行代码时,它会打印每个字符出现1

list1 = ['barack', 'obar?ma', '?america?', 'war', 'russia?', 'mak?er'] 

common = set.intersection(*map(set,list1))

new_list = list(common)

for i in list1:
    for a in new_list:
        if a in i:
            x = new_list.count(a)
            print([i] + [a])
            print(x)

Hi what I am trying to do is count the specific occurrences of the characters common to each string in the list below and print out each string and how many times the common characters appear
example
barack a appears 2
barack r appears 1
when I run my code it prints that each character appears 1

list1 = ['barack', 'obar?ma', '?america?', 'war', 'russia?', 'mak?er'] 

common = set.intersection(*map(set,list1))

new_list = list(common)

for i in list1:
    for a in new_list:
        if a in i:
            x = new_list.count(a)
            print([i] + [a])
            print(x)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千紇 2025-01-26 16:47:41

将 x = new_list.count(a) 更改为 x = i.count(a)。目前您正在计算 'a' 中有多少个 a;您想要计算 barack 中有多少个 a

经过此修改的新代码:

list1 = ['barack', 'obar?ma', '?america?', 'war', 'russia?', 'mak?er']

common = set.intersection(*map(set,list1))

new_list = list(common)

for i in list1:
    for a in new_list:
        if a in i:
            x = i.count(a)
            print([i] + [a])
            print(x)

打印:

['barack', 'a']
2
['barack', 'r']
1
['obar?ma', 'a']
2
['obar?ma', 'r']
1
['?america?', 'a']
2
['?america?', 'r']
1
['war', 'a']
1
['war', 'r']
1
['russia?', 'a']
1
['russia?', 'r']
1
['mak?er', 'a']
1
['mak?er', 'r']
1

Change x = new_list.count(a) to x = i.count(a). At the moment you are counting how many as in 'a'; you want to count how many as in barack.

The new code with this modification:

list1 = ['barack', 'obar?ma', '?america?', 'war', 'russia?', 'mak?er']

common = set.intersection(*map(set,list1))

new_list = list(common)

for i in list1:
    for a in new_list:
        if a in i:
            x = i.count(a)
            print([i] + [a])
            print(x)

prints this:

['barack', 'a']
2
['barack', 'r']
1
['obar?ma', 'a']
2
['obar?ma', 'r']
1
['?america?', 'a']
2
['?america?', 'r']
1
['war', 'a']
1
['war', 'r']
1
['russia?', 'a']
1
['russia?', 'r']
1
['mak?er', 'a']
1
['mak?er', 'r']
1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文