簡體   English   中英

給定一個字符串列表,返回出現在多個字符串中的字符

[英]Given a list of strings, return characters that appear in more than one string

我正在嘗試實現一個函數,該函數接收可變數量的字符串並返回至少出現在兩個字符串中的字符:

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

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

從字符串中刪除重復項(通過創建每個字符串的字符集),然后創建一個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'}

使用setcollections.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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM