我在代码部分的下面有这段代码。
我必须返回一个列表,其中第二个参数中的所有函数 已经以元组的格式类型应用于第一个参数的元素 例如这两个列表
objs = [(1,2),[1,3,4,5,6,7],[0]]
funcs = [len,sum]
I must return #--> [(2, 3, <class 'tuple'>), (6, 26, <class 'list'>), (1, 0, <class 'list'>)]
谢谢您的帮助
objs = [(1,2),[1,3,4,5,6,7],[0]]
funcs = [len,sum,type]
def calc_len(objs, funcs):
t = []
z = []
for i in objs:
print(i) # To check output
z.append(i) # Create a list Z of "i"
#print("Z : ", z)
# Then I apply each function from the second list
for j in funcs:
if j==len:
print("Lenght:",j(i))
elif j==sum:
print("Sum :" ,j(i))
else:
print("Type :",j(i))
t.append(j(i))
# How Turn that list into a tuple and add to list to return
print (t)
print(calc_len(objs, funcs))
Should return #--> [(2, 3), (6, 26), (1, 0)]
结果下方
[358]: print(calc_len(objs, funcs))
(1, 2)
Z : [(1, 2)]
Lenght: 2
Sum : 3
Type : <class 'tuple'>
[2, 3, <class 'tuple'>]
[1, 3, 4, 5, 6, 7]
Z : [(1, 2), [1, 3, 4, 5, 6, 7]]
Lenght: 6
Sum : 26
Type : <class 'list'>
[2, 3, <class 'tuple'>, 6, 26, <class 'list'>]
[0]
Z : [(1, 2), [1, 3, 4, 5, 6, 7], [0]]
Lenght: 1
Sum : 0
Type : <class 'list'>
[2, 3, <class 'tuple'>, 6, 26, <class 'list'>, 1, 0, <class 'list'>]
答案 0 :(得分:0)
您可以使用列表推导将每个函数应用于参数,并使用结果构建元组。
result = [ tuple(f(x) for f in funcs) for x in objs ]
答案 1 :(得分:0)
objs = [(1,2),[1,3,4,5,6,7],[0]]
result = [(len(item),sum(item),type(item)) for item in objs]
print (result)
输出:
[(2, 3, <class 'tuple'>), (6, 26, <class 'list'>), (1, 0, <class 'list'>)]
。
objs = [(1,2),[1,3,4,5,6,7],[0]]
funcs = ['len','sum','type']
def calc_len(objs, funcs):
result = []
for item in objs:
r = []
for func in funcs:
if func == 'len':
r.append(len(item))
if func == 'sum':
r.append(sum(item))
if func == 'type':
r.append(type(item))
result.append(tuple(r))
return result
print(calc_len(objs, funcs))
输出:
[(2, 3, <class 'tuple'>), (6, 26, <class 'list'>), (1, 0, <class 'list'>)]