python - 在多个字典中查找常用字母 - python
问题描述
我正在使用给定的字符串制作代码返回字符。我知道使用计数器功能时更容易使用,但我尽量不使用它。
这是我的代码
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
.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)])
推荐阅读
- javascript - ReactJS:尝试使用表单登录后呈现新屏幕,从 Express JSON 获取数据
- javascript - 设置 HTML 框架 src 在 Safari 中不起作用
- ios - 当mapview是属性时如何使用点击标记事件
- c# - InvalidateVisual 通知
- regex - Python regex (.*?) 没有给出输出
- docusignapi - DocuSign - 随机 UNABLE_TO_CONVERT_DOCUMENT 错误
- javascript - 使用 canvas + css 动画构建棋盘游戏
- python - 从列表中选择要放入图表的值
- php - PHP preg_split 添加了一个无法被 array_filter 清除的空白数组键,因为其中有一个“空格”
- bash - Linux在文本文件中打印交替的2行