【问题标题】:Check if a list of strings contains letters from another list检查字符串列表是否包含来自另一个列表的字母
【发布时间】:2018-11-13 13:24:12
【问题描述】:

所以我有两个列表:

vocabulary = ['a','b','c']
sentences = ['a a b b c c', 'a c b c', 'b c c a b']

我想计算词汇表中的字母出现在列表句子的字符串中的次数。

所以我希望输出是:

a = 4
b = 5
c = 6

我的程序:

counter = Counter()
for word in sentences:
    if word in vocabulary:
        counter.update(word)
print(counter)

但我不断得到输出:

Counter()

【问题讨论】:

    标签: python string python-3.x dictionary counter


    【解决方案1】:

    Counterdict 的子类。 dict.update 接受另一个字典或可迭代的对。但是你只提供了一个字符。

    在这种情况下,您可以链接您的字符串列表并传递给Counter,然后通过字典理解过滤结果:

    from collections import Counter
    from itertools import chain
    
    vocabulary = ['a','b','c']
    sentences = ['a a b b c c', 'a c b c', 'b c c a b']
    
    vocab_set = set(vocabulary)
    c = Counter(chain.from_iterable(sentences))
    res = {k: v for k, v in c.items() if k in vocab_set}
    
    {'a': 4, 'b': 5, 'c': 6}
    

    【讨论】:

      【解决方案2】:

      这样就可以了,不需要import

      vocabulary = ['a','b','c']
      sentences = ['a a b b c c', 'a c b c', 'b c c a b']
      
      data = ''.join(sentences)
      
      for v in vocabulary:
          print('{}: {}'.format(v, data.count(v)))
      
      a: 4
      b: 5
      c: 6
      

      【讨论】:

      • 值得注意的是,这是以时间复杂度为代价的 O(m * n) vs O(n) .
      【解决方案3】:

      O(n) 解决方案,没有import

      vocabulary = ['a', 'b', 'c']
      sentences = ['a a b b c c', 'a c b c', 'b c c a b']
      
      counts = {}
      vocab_set = set(vocabulary)
      for sentence in sentences:
          for ch in sentence:
              if ch in vocab_set:
                  counts[ch] = counts.get(ch, 0) + 1
      
      print(counts)
      

      输出

      {'c': 6, 'a': 4, 'b': 5}
      

      【讨论】:

        猜你喜欢
        • 2012-07-04
        • 2020-07-19
        • 2022-10-23
        • 1970-01-01
        • 2019-07-21
        • 2013-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多