leetcode 刷题笔记

1、将list转化为字典

 for i in range(len(A)):
            each = dict()
            for j in A[i]:
                if j not in each:
                    each[j] = 1
                else:
                    each[j] += 1

reduce() 函数会对参数序列中元素进行累积。

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

reduce(function, iterable[, initializer])
  • function -- 函数,有两个参数
  • iterable -- 可迭代对象
  • initializer -- 可选,初始参数
>>>def add(x, y) :            # 两数相加
...     return x + y
... 
>>> reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
15
>>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
15
A = ["bella","label","roller"]
number = []
for i in range(len(A)):
    each = dict()
    for j in A[i]:
        if j not in each:
            each[j] = 1
        else:
            each[j] += 1
    number.append(each)
result = []
from functools import reduce
#找出每个list中存在一样keys值的值,
#dict_keys(['b', 'e', 'l', 'a'])
#dict_keys(['l', 'a', 'b', 'e'])
#dict_keys(['r', 'o', 'l', 'e'])
union = list(reduce(lambda x,y:x&y, map(dict.keys, number)))#dict.keys需对llist进行操作
for i in union:#union  ['l', 'e']
    result.extend([i] * min([k[i] for k in number]))
#['l', 'l', 'e']
原文地址:https://www.cnblogs.com/xxupup/p/10770981.html