【问题标题】:How do I find the count of a substring in a string when substring and string both are lists?当子字符串和字符串都是列表时,如何找到字符串中子字符串的计数?
【发布时间】:2017-09-04 07:45:17
【问题描述】:

我正在尝试计算一个列表 (X) 中出现在另一个列表 (Y) 中的单词。我正在迭代的列表在一个字符串中有多个单词。

例子:

X = ['abc def ghi klm', 'xyz bef mno', 'jkl mno pqr abc', 'xyz mno def']

Y = ['def', 'xyz', 'abc', 'tuv']

输出应该是这样的:

Y 项的数量:

def = 2
xyz = 2
abc = 2

我尝试了什么:

for obj in X:
    for item in Y:
        if obj in item:
            freq = obj.count(item)
            print (freq)

我也尝试过列表理解,但我认为情况并非如此。

【问题讨论】:

  • 请展示你是如何解决这个问题的。
  • 我投票结束这个话题
  • SO 不是代码编写服务
  • def 出现两次。为什么应该是def = 1

标签: python string python-3.x list loops


【解决方案1】:

使用内置sum()函数的短一行解决方案:

x = ['abc def ghi klm', 'xyz bef mno', 'jkl mno pqr abc', 'xyz mno def']
y = ['def', 'xyz', 'abc', 'tuv']
result = {i: sum(w.count(i) for w in x) for i in y}

print(result)

输出:

{'def': 2, 'xyz': 2, 'tuv': 0, 'abc': 2}

---------

或者用collections.Counter对象:

import collections
x = ['abc def ghi klm', 'xyz bef mno', 'jkl mno pqr abc', 'xyz mno def']
y = ['def', 'xyz', 'abc', 'tuv']

c = collections.Counter(' '.join(x).split())
result = {i: c[i] for i in y if i in c}

print(result)

输出:

{'abc': 2, 'def': 2, 'xyz': 2}

【讨论】:

  • sum() oneliner 不起作用,因为 X 中的单个字符串中有多个单词。因此它会将 'abc def ghi klm' 作为单个元素进行检查
  • @Vinny,错了,i in w 将检查是否为 ex。 def 出现在 abc def ghi klm 中。只有当单个 x 项目包含重复的 y 项目时,您的怀疑才可能是合理的。我没有看到这样的输入和这样的条件。所以它会起作用(直到 OP 宣布新条件)
  • @Vinny,此外,我已经扩展了我的 sum 方法以应对潜在情况“如果单个 x 项目包含重复的 y 项目”。它肯定会工作
【解决方案2】:

您可以做的是遍历 X 列表,操作您的字符串以在空格上拆分(这样您就可以分隔每个单词),然后使用 Counter 类创建一个字典,该字典仅计算 Y 中存在的项目的出现次数

>>> import itertools
>>> from collections import Counter
>>> c = Counter()
>>> for word in X:
        words = word.split(' ')
        words = [w for w in words if w in Y]
        c.update(words)

>>> c
Counter({'xyz': 3, 'abc': 3, 'def': 3, 'tuv': 1})

【讨论】:

    【解决方案3】:

    不确定我是否能得到你所需要的(在你的例子中不应该是def = 2?),但我认为这可能接近你所需要的:

    from collections import defaultdict
    from itertools import product
    
    counts = defaultdict(int)
    for x, y in product(X, Y):
        if y in x:
            counts[y] += 1
    

    您可以通过运行检查输出:

    for k, v in counts.items():
        print('{} = {}'.format(k, v))
    

    哪个打印:

    def = 2
    abc = 2
    xyz = 2
    

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2021-04-21
      • 2023-04-06
      相关资源
      最近更新 更多