亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

至尊寶的傳說 2023-05-09 14:49:31
我正在用給定的字符串制作代碼返回字符。我知道使用計數器功能更容易使用,但我盡量不使用它。這是我的代碼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"]
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

reduce.only 添加一行的可能解決方案:


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)])


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號