我被这个问题困住了,因为我对python中的函数式编程相当陌生。任何帮助都将不胜感激
注意:我知道使用map更简单,因为我们可以使用iterable,但我需要一些方法来实现这一点,只使用lambda函数
Given the following list, ages of 25 people:
ages = [79, 91, 25, 22, 95, 69, 47, 87, 87, 2, 13, 94, 50, 73, 29, 87, 81, 51, 32, 69, 10, 91, 45, 7,
51]
Q: Make a new list in which you multiply each age with a random number between 1 to 10
(Generate a random number for each age and multiply them together). Only use Lambda
Function for the multiplication. (You can use random generator provided by in python to
generate the random numbers)
这就是我到目前为止所做的:
import random
inconsistent = []
ages = [79, 91, 25, 22, 95, 69, 47, 87, 87, 2, 13, 94, 50, 73, 29, 87, 81, 51, 32, 69, 10, 91, 45, 7,
51]
for i in range(25):
inconsistent.append(random.randint(1,10))
print(inconsistent)
x = lambda a,b: a*b
x(ages, inconsistent)
以下是我得到的错误:
TypeError Traceback (most recent call last)
<ipython-input-24-646727e92091> in <module>
10
11 x = lambda a,b: a*b
---> 12 x(ages, inconsistent)
<ipython-input-24-646727e92091> in <lambda>(a, b)
9 print(inconsistent)
10
---> 11 x = lambda a,b: a*b
12 x(ages, inconsistent)
TypeError: can't multiply sequence by non-int of type 'list'
使用
map
。Map可以将lambda
作为第一个参数,将iterable
作为第二个参数就你而言
您可以使用列表理解:
相关问题 更多 >
编程相关推荐