【问题标题】:How to subtract numbers from a set from another set in python?如何从python中的另一个集合中减去一个集合中的数字?
【发布时间】:2016-06-28 02:15:19
【问题描述】:

我想减去两个列表中的值。

a = [1,2,3,4]
b = [1,0,1,5]
c = a - b
#c should be = [0,2,2,-1]

How can I add the corresponding elements of several lists of numbers? 的答案是类似的,但上面的很多答案只适用于添加。

如果可能,请回答如何减去。

【问题讨论】:

  • 你的意思是listsets 在 Python 中是无序的。
  • How can I add the corresponding elements of several lists of numbers? 的可能重复项。它不完全一样,但它足够接近,可以作为骗子关闭。
  • 如果你的大部分代码都是这样的,你应该试试R。用ab作为向量,c <- a-b已经可以做你想做的事了。

标签: python python-3.x


【解决方案1】:

itertools.starmap 可能对您有用:

>>> a = [1,2,3,4]
>>> b = [1,0,1,5]
>>> 
>>> import itertools as it
>>> 
>>> import operator as op
>>> 
>>> list(it.starmap(op.sub, zip(a,b)))
[0, 2, 2, -1]

或者:

>>> [item for item in it.starmap(op.sub, zip(a,b))]
[0, 2, 2, -1]

【讨论】:

    【解决方案2】:
    c = [a1 - b1 for (a1, b1) in zip(a, b)]
    

    【讨论】:

      【解决方案3】:

      大多数人使用numpy 进行数值运算(尽管 p.magalhaes 有“纯”python 的答案)。

      import numpy as np
      a=np.array([1,2,3,4])
      b=np.array([1,0,1,5])
      c = a - b
      c
      

      返回

      array([ 0,  2,  2, -1])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 1970-01-01
        • 2015-09-14
        • 1970-01-01
        相关资源
        最近更新 更多