【问题标题】:Given a list of strings, return characters that appear in more than one string给定一个字符串列表,返回出现在多个字符串中的字符
【发布时间】:2020-01-06 16:59:26
【问题描述】:

我正在尝试实现一个函数,它接收可变数量的字符串并返回至少出现在两个字符串中的字符:

test_strings = ["hello", "world", "python", ]

print(test(*strings))
{'h', 'l', 'o'}

【问题讨论】:

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


    【解决方案1】:

    从字符串中删除重复项(通过设置每个字符串的字符集),然后创建一个 Counter 来计算每个字符出现在的输入字符串的数量

    from collections import Counter
    from itertools import chain
    
    def test(*strings, n=2):
        sets = (set(string) for string in strings)
        counter = Counter(chain.from_iterable(sets))
        return {char for char, count in counter.items() if count >= n}
    
    
    print(test("hello", "world", "python"))  # {'o', 'h', 'l'}
    

    【讨论】:

      【解决方案2】:

      使用setscollections.Counter 的单行代码:

      from collections import Counter
      
      test_strings = ["hello", "world", "python"]
      
      letters = {k for k, v in Counter([l for x in test_strings for l in set(x)]).items() if v > 1}
      

      输出:

      >>> letters
      {'o', 'l', 'h'}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 2013-05-07
        • 1970-01-01
        • 2021-04-30
        相关资源
        最近更新 更多