我想定义一个函数,该函数接受2个参数(x1, x2)
并从x1
遍历0 to 100
并返回该函数的总和。
结果的简化版本应如下所示:
f = lambda x1, x2: a*x1 + b*x2
x1
应在i
,i = [0, 1, ..., 100]
范围内更改f1 = f(0, x2) + f(1, x2) + f(3, x2) + ... + f(100, x2)
如何定义以正确格式返回上述
f1
函数的函数?我在下面尝试过,但是没有用:
f = lambda x1, x2: a*x1 + b*x2
f1 = lambda x2: (lambda x1=range(100):f(x1,x2))()
最佳答案
什么是a
和b
?我假设常数
为什么不使用list comprehension
?
a=1
b=2
x2 = 4 # I assume this is a constant
output = [a*x1 + b*x2 for x1 in range(101)] # x1 goes from 0 to 100
print(output)
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108]
或者,
f = lambda x1, x2: a*x1 + b*x2
f1 = lambda x2: sum(f(x1,x2) for x1 in range(101)) # x1 goes from 0 to 100
关于python - 如何在for循环中使用lambda?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59364277/