【问题标题】:How to mathematically subtract two lists in python? [duplicate]如何在python中数学减去两个列表? [复制]
【发布时间】:2014-04-19 17:37:36
【问题描述】:

我知道 python 不支持列表的减法,但是有一些方法可以省略两个列表之间的公共元素。但是我想要做的是将一个列表中的每个元素分别与另一个列表中的相应元素相减,并将结果作为输出列表返回。我该怎么做?

     A = [3, 4, 6, 7]
     B = [1, 3, 6, 3]
     print A - B  #Should print [2, 1, 0, 4]

【问题讨论】:

    标签: python list subtraction


    【解决方案1】:

    operatormap 模块一起使用:

    >>> A = [3, 4, 6, 7]
    >>> B = [1, 3, 6, 3]
    >>> map(operator.sub, A, B)
    [2, 1, 0, 4]
    

    正如下面提到的@SethMMorton,在 Python 3 中,你需要这个

    >>> A = [3, 4, 6, 7]
    >>> B = [1, 3, 6, 3]
    >>> list(map(operator.sub, A, B))
    [2, 1, 0, 4]
    

    因为,map 在 Python 中会返回一个迭代器。

    【讨论】:

    • 注意,在 python 3 上,这不会返回 list,而是一个 map 对象。您需要list(map(operator.sub, A, B)) 才能获得相同的结果。
    • @SethMMorton 不错。我会将其添加到答案中
    【解决方案2】:

    您可以使用ziplist comprehension

    >>> A = [3, 4, 6, 7]
    >>> B = [1, 3, 6, 3]
    >>> zip(A, B) # Just to demonstrate
    [(3, 1), (4, 3), (6, 6), (7, 3)]
    >>> [x - y for x, y in zip(A, B)]
    [2, 1, 0, 4]
    >>>
    

    【讨论】:

      【解决方案3】:

      试试类似的东西

      def substract_lists(a, b):
          for i, val in enumerate(a):
                  val = val - b[i]
          return a
      

      【讨论】:

        猜你喜欢
        • 2012-01-01
        • 2017-09-29
        • 2021-04-21
        • 2021-01-08
        • 2021-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多