簡體   English   中英

在多個字典中查找常用字母 - python

[英]Find common alphabets in multiple dictionaries - python

我正在使用給定的字符串制作代碼返回字符。 我知道使用計數器 function 時它更容易使用,但我盡量不使用它。

這是我的代碼

class Solution:
    def commonChars(self, A):
        dic = {}
        for i in range(len(A)):
            A[i] = list(A[i])
            dic[i] = self.checkLetter(A[i])
        print(dic)
        
    def checkLetter(self, Letter_list) : 
        letter_cnt = {}
        for l in Letter_list:
            if l in letter_cnt : letter_cnt[l] += 1
            else : letter_cnt[l] = 1
        return letter_cnt

我已經用字典做了一個字母計數器,但我不知道下一步該做什么。 你能給我一個提示嗎?

# given input_1 : ["bella","label","roller"]
# expected output is e,l,l because it is common in every string in the given list
>>> ["e","l","l"]

# result of my code
>>> {0: {'a': 1, 'b': 1, 'e': 1, 'l': 2}, 1: {'a': 1, 'b': 1, 'e': 1, 'l': 2}, 2: {'r': 2, 'e': 1, 'l': 2, 'o': 1}}

# given input_2 : ["cool","lock","cook"]
# expected output
>>> ["c","o"]

reduce的可能解決方案。僅添加一行:

from functools import reduce


class Solution:
    def commonChars(self, A):
        dic = {}
        for i in range(len(A)):
            A[i] = list(A[i])
            dic[i] = self.checkLetter(A[i])
        print([char for char, count in reduce(lambda x, y:{k:min(x[k], y[k]) for k,v in x.items() if y.get(k)}, dic.values()).items() for _ in range(count)])

    def checkLetter(self, Letter_list):
        letter_cnt = {}
        for l in Letter_list:
            if l in letter_cnt:
                letter_cnt[l] += 1
            else:
                letter_cnt[l] = 1
        return letter_cnt


s = Solution()
s.commonChars(["bella","label","roller"])
# ['e', 'l', 'l']
s.commonChars(["cool","lock","cook"])
# ['c', 'o']

拆分它:

result_dict = reduce(lambda x, y:{k:min(x[k], y[k]) for k,v in x.items() if y.get(k)}, dic.values())

print([char for char, count in result_dict.items() for _ in range(count)])

暫無
暫無

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

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