用Python 2.5减去两个列表
我写了一个函数,它用两个列表中的值进行减法运算,代码如下:
import sys,os
import math
c1 = [10]
c2 = [5]
d1 = [8]
d2 = [4]
x = d2 - c2
y = d1 - c1
z = x*x
w = y*y
answer = sqrt(z + w)
print answer
我遇到的错误是:TypeError: unsupported operand type(s) for -: 'list' and 'list'。这个错误的意思是说,不能直接对两个列表进行减法运算。
我该怎么解决这个问题呢?因为在 d2-d1 和 c2-c1 这两行代码中,减法是不能在列表之间进行的。有没有类似于平方根(sqrt)的内置函数可以用来处理列表的减法呢?
3 个回答
1
你不能一次性把整个列表减去,就算列表里只有一个项目也不行。你得一个一个地来处理。你可以用循环来做,或者用一个叫做map的方式。下面是用map的写法:
import operator.sub
map(operator.sub, d2, c2)
map(operator.sub, d1, c1)
2
你是想做这个吗?
import math
c = [10,5]
d = [8,4]
x = d[1] - c[1]
y = d[0] - c[0]
z = x*x
w = y*y
print math.sqrt(z+w)
1
你现在使用的是只有一个元素的列表;如果你想要进行特定的计算,只需要去掉大括号就可以了。我假设你其实是有多个值的列表。一个合理的解决方案是结合使用 map()
函数,它可以对一个或多个列表中的每个元素应用一个函数,还有一些来自 operator
模块的函数,这些函数可以把很多 Python 的运算符(比如 +
和 -
)变成函数。
首先,我们先准备一些列表。
>>> import random
>>> d1 = [random.randrange(10) for ignored in range(10)]
>>> d2 = [random.randrange(10) for ignored in range(10)]
>>> c1 = [random.randrange(10) for ignored in range(10)]
>>> c2 = [random.randrange(10) for ignored in range(10)]
>>> c1
[1, 1, 7, 5, 5, 7, 4, 0, 7, 2]
>>> c2
[9, 2, 7, 7, 1, 1, 9, 3, 6, 8]
>>> d1
[0, 3, 4, 8, 9, 0, 7, 1, 6, 5]
>>> d2
[3, 9, 5, 2, 1, 9, 2, 7, 9, 5]
接下来,我们只需要把你每个操作替换成一个 map
调用,调用相应的 operator.*
函数。
>>> import operator
>>> x = map(operator.sub, d2, c2)
>>> y = map(operator.sub, d2, c2)
>>> z = map(operator.mul, x, x)
>>> w = map(operator.mul, y, y)
>>> import math
>>> answer = map(math.sqrt, map(operator.add, z, w))
>>> print answer
[8.48528137423857, 9.899494936611665, 2.8284271247461903, 7.0710678118654755, 0.0, 11.313708498984761, 9.899494936611665, 5.656854249492381, 4.242640687119285, 4.242640687119285]
>>>