开发者

using python 2.5 to subtract two lists

开发者 https://www.devze.com 2023-04-04 18:30 出处:网络
i have made a function which usessubtraction of two values stored in two lists as follow开发者_StackOverflow社区s:

i have made a function which uses subtraction of two values stored in two lists as follow开发者_StackOverflow社区s:

     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

My error is: TypeError: unsupported operand type(s) for -: 'list' and 'list'

How can I get over the error that occurs due to subtraction not being possible between two lists, i.e., in lines d2-d1 and c2-c1? Is there a built-in function in the math module similar to sqrt that i might use to subtract lists?


Is this what you are trying to do?

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)


You're using one element lists; If you want to perform that calculation specifically, just remove the braces. I'll assume that you actually do have multi-valued lists. A reasonable solution is to combine map(), which applies a function to each element in one or more lists, as well as some of the functions from the operator module, which turn many python operators (like + and -) into functions.

First well just set up some lists.

>>> 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]

Next we just replace each of your operations into a map call to the corresponding 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]
>>> 


You can't subtract a whole list at once like that, even if there is only one item in the list. You have to do them one at a time. You could do it in a loop, or with a map. Here it is with a map:

import operator.sub
map(operator.sub, d2, c2)
map(operator.sub, d1, c1)
0

精彩评论

暂无评论...
验证码 换一张
取 消