[英]Python 3 - Find strings that appear in more than one list, the list are populated from function arguments
[英]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'}
使用set和collections.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.