使用列表的2个索引作为映射中lambda的参数

2024-09-29 00:23:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在接收数据,并将其放入一个列表中,希望使用pythonmap&lambda计算新列表的两个索引。你知道吗

我目前正在使用这个代码,这给了我一个错误

TypeError: argument 2 to map() must support iteration

for i in range(int(raw_input())):
    a = map(float, raw_input().split(' '))
    print map(lambda x, y: x / (y^2), a[0], a[1])

我使用的数据

47 1.30
84 2.45
52 1.61
118 2.05
70 1.67
75 1.58

Tags: tolambda代码mapsupport列表inputraw
3条回答

您可以使用适合您的用例的reduce,而不是使用map

for i in range(int(raw_input())):
    a = map(float, raw_input().split(' '))
    print reduce(lambda x, y: x / (y^2), a)

https://docs.python.org/2/library/functions.html#map

map(function, iterable, ...) Apply function to every item of iterable and return a list of the results...

a是可iterable的,因为raw_input().split(' ')是可iterable的,但是a[0]a[1]不是。你知道吗

你应该print a[0] / a[1]**2

正确的输入

6
47 1.30
84 2.45
52 1.61
118 2.05
70 1.67
75 1.58

和代码

for i in range(int(raw_input())):
    a = map(float, raw_input().split(' '))
    print a[0] / a[1]**2

可以将数组作为参数传递给lambda,并使用其索引访问lambda中的元素:

print map(lambda x: x[0]/(x[1]**2), [a])

另外,您使用的是位异或运算符(^),而不是“幂”运算符(**)

但是。。。我不认为在这里使用lambda有什么意义,您只需要对这两个元素进行一些计算。 所以你可以做:

print a[0]/a[1]**2

相关问题 更多 >