Пример #1
0
def count_occurences(arr, val):
    """
    return count of val from your array
    """
    return reduce(
        (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
        arr)
Пример #2
0
def deep_get(dictionary, *keys):
    return reduce(lambda d, key: d.get(key) if d else None, keys, dictionary)
Пример #3
0
valor_dobrado = map(dobro, valor)

for v in valor_dobrado:
	print(v)

valor_dobrado = list(valor_dobrado)
print(valor_dobrado)


#reduce
from functool import reduce
def soma (x,y):
	return x+y

lista = [1,23,54,3,435,353,63,54,34,3,323]

soma = reduce(soma, lista)

print(soma)


#zip

lista1 = [1,2,3,4,5]
lista2 = ["abacate", "bola", "cachorro", "dinheiro","elefante"]
lista3 = ["R$ 2,00","R$ 5,00","R$ 21,00","R$ 32,00","R$ 552,00"]


for numero, nome, valor in zip(lista1, lista2, lista3):
	print(numero, nome, valor)
Пример #4
0
# Extract, map, reduce
from functool import reduce

volume = reduce(lambda x, y: x * y, map(int, input.strip().split()))
printf(f"{volume=}")

# Filter
names = ["Jhon", "Nike", "Mikle", "Leo", "Alex"]
names_starts_with_a = filter(lambda name: name.startswith("A"), names)
print(tuple(names_starts_with_a))

# Copy list value
indexes = [1, 2]
another_index = indexes[:]
# Revert
another_indexes[::-1]

# all true
a, b, c, d, e = True
if all(a, b, c, d, e):
    print("ok")
#any true
if any(a, b, c, d, e):
    print("ok")

# Config
group_to_method = {
    "admin": process_admin_request,
    "manager": process_manager_request,
    "client": process_client_request
}
Пример #5
0
print(values)
# map传入的第一个参数是r,为函数本身,由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list
# 
# 使用另外一种方法实现
L=[]
for n in [1,2,3,4,5,6,7,8]:
	L.append(f(n))
print(L)
# 但是第二中方式要繁琐并且不能很快的看出把f函数作用到了list上面
# map是一种高阶函数。
# 
# reduce
# reduce把一个函数作用在一个序列[x1,x2,x3,x4.....]上,这个函数鼻血接受两个参数,reduce把结果继续和序列的下一个元素做累积计算。
# reduce(fn,[x1,x2,x3]) = f(f(f(x1,x2),x3),x4)

from functool import reduce
def add(x,y):
	return x*y
reduce(add,[1,3,5,7,9])

# 将一个字符串拆分为int并进行后续的操作
from functool import reduce
def add(x,y):
	return x*10+y
def char2num(s):
	return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]
reduce(add,map(char2num,'13579'))
# 13579运行结果
# 还可以简化为这样
reduce(lambda x,y:x*10+y,map(char2num,'13579'))