简体   繁体   English

在 Python 中减去 2 个列表

[英]Subtracting 2 lists in Python

Right now I have vector3 values represented as lists.现在我将 vector3 值表示为列表。 is there a way to subtract 2 of these like vector3 values, like有没有办法减去其中的 2 个,例如 vector3 值,例如

[2,2,2] - [1,1,1] = [1,1,1]

Should I use tuples?我应该使用元组吗?

If none of them defines these operands on these types, can I define it instead?如果他们都没有在这些类型上定义这些操作数,我可以定义它吗?

If not, should I create a new vector3 class?如果没有,我应该创建一个新的 vector3 类吗?

If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy .如果这是你最终经常做的事情,并且有不同的操作,你可能应该创建一个类来处理这样的情况,或者更好地使用像Numpy这样的库。

Otherwise, look for list comprehensions used with the zip builtin function:否则,查找与zip内置函数一起使用的列表推导式:

[a_i - b_i for a_i, b_i in zip(a, b)]

Here's an alternative to list comprehensions.这是列表推导式的替代方法。 Map iterates through the list(s) (the latter arguments), doing so simulataneously, and passes their elements as arguments to the function (the first arg). Map 遍历列表(后一个参数),同时进行,并将它们的元素作为参数传递给函数(第一个参数)。 It returns the resulting list.它返回结果列表。

import operator
map(operator.sub, a, b)

This code because has less syntax (which is more aesthetic for me), and apparently it's 40% faster for lists of length 5 (see bobince's comment).这段代码因为语法较少(这对我来说更美观),显然长度为 5 的列表快了 40%(参见 bobince 的评论)。 Still, either solution will work.尽管如此,任何一种解决方案都将奏效。

If your lists are a and b, you can do:如果您的列表是 a 和 b,您可以执行以下操作:

map(int.__sub__, a, b)

But you probably shouldn't.但你可能不应该。 No one will know what it means.没有人会知道这意味着什么。

I'd have to recommend NumPy as well我也必须推荐NumPy

Not only is it faster for doing vector math, but it also has a ton of convenience functions.它不仅进行向量数学运算速度更快,而且还具有大量便利功能。

If you want something even faster for 1d vectors, try vop如果你想要更快的一维向量,试试vop

It's similar to MatLab, but free and stuff.它类似于 MatLab,但免费。 Here's an example of what you'd do这是你要做的一个例子

from numpy import matrix
a = matrix((2,2,2))
b = matrix((1,1,1))
ret = a - b
print ret
>> [[1 1 1]]

Boom.繁荣。

import numpy as np
a = [2,2,2]
b = [1,1,1]
np.subtract(a,b)

如果你有两个名为“a”和“b”的列表,你可以这样做: [m - n for m,n in zip(a,b)]

A slightly different Vector class.一个稍微不同的 Vector 类。

class Vector( object ):
    def __init__(self, *data):
        self.data = data
    def __repr__(self):
        return repr(self.data) 
    def __add__(self, other):
        return tuple( (a+b for a,b in zip(self.data, other.data) ) )  
    def __sub__(self, other):
        return tuple( (a-b for a,b in zip(self.data, other.data) ) )

Vector(1, 2, 3) - Vector(1, 1, 1)

For the one who used to code on Pycharm, it also revives others as well.对于曾经在 Pycharm 上编码的人来说,它也让其他人重振旗鼓。

 import operator
 Arr1=[1,2,3,45]
 Arr2=[3,4,56,78]
 print(list(map(operator.sub,Arr1,Arr2)))

If you plan on performing more than simple one liners, it would be better to implement your own class and override the appropriate operators as they apply to your case.如果您计划执行多个简单的衬垫,最好实现您自己的类并覆盖适用于您的案例的适当运算符。

Taken from Mathematics in Python :取自Python 中的数学

class Vector:

  def __init__(self, data):
    self.data = data

  def __repr__(self):
    return repr(self.data)  

  def __add__(self, other):
    data = []
    for j in range(len(self.data)):
      data.append(self.data[j] + other.data[j])
    return Vector(data)  

x = Vector([1, 2, 3])    
print x + x

The combination of map and lambda functions in Python is a good solution for this kind of problem: Python 中maplambda函数的结合,很好地解决了这类问题:

a = [2,2,2]
b = [1,1,1]
map(lambda x,y: x-y, a,b)

zip function is another good choice, as demonstrated by @UncleZeiv zip函数是另一个不错的选择,如@UncleZeiv 所示

arr1=[1,2,3]
arr2=[2,1,3]
ls=[arr2-arr1 for arr1,arr2 in zip(arr1,arr2)]
print(ls)
>>[1,-1,0]

This answer shows how to write "normal/easily understandable" pythonic code.这个答案展示了如何编写“正常/易于理解”的pythonic代码。

I suggest not using zip as not really everyone knows about it.我建议不要使用zip因为并不是每个人都知道它。


The solutions use list comprehensions and common built-in functions.解决方案使用列表推导式和常见的内置函数。


Alternative 1 (Recommended):备选方案 1(推荐):

a = [2, 2, 2]
b = [1, 1, 1]
result = [a[i] - b[i] for i in range(len(a))]

Recommended as it only uses the most basic functions in Python推荐,因为它只使用 Python 中最基本的功能


Alternative 2:备选方案 2:

a = [2, 2, 2]
b = [1, 1, 1]
result = [x - b[i] for i, x in enumerate(a)]

Alternative 3 (as mentioned by BioCoder ):备选方案 3(如BioCoder 所述):

a = [2, 2, 2]
b = [1, 1, 1]
result = list(map(lambda x, y: x - y, a, b))

Many solutions have been suggested.已经提出了许多解决方案。

If speed is of interest, here is a review of the different solutions with respect to speed (from fastest to slowest)如果对速度感兴趣,这里是关于速度(从最快到最慢)的不同解决方案的回顾

import timeit
import operator

a = [2,2,2]
b = [1,1,1]  # we want to obtain c = [2,2,2] - [1,1,1] = [1,1,1

%timeit map(operator.sub, a, b)
176 ns ± 7.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit map(int.__sub__, a, b)
179 ns ± 4.95 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit map(lambda x,y: x-y, a,b)
189 ns ± 8.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit [a_i - b_i for a_i, b_i in zip(a, b)]
421 ns ± 18.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit [x - b[i] for i, x in enumerate(a)]
452 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each

%timeit [a[i] - b[i] for i in range(len(a))]
530 ns ± 16.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit list(map(lambda x, y: x - y, a, b))
546 ns ± 16.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.subtract(a,b)
2.68 µs ± 80.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit list(np.array(a) - np.array(b))
2.82 µs ± 113 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.matrix(a) - np.matrix(b)
12.3 µs ± 437 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Using map is clearly the fastest.使用map显然是最快的。 Surprisingly, numpy is the slowest.令人惊讶的是, numpy是最慢的。 It turns out that the cost of first converting the lists a and b to a numpy array is a bottleneck that outweighs any efficiency gains from vectorization.事实证明,首先将列表ab转换为numpy数组的成本是一个瓶颈,它超过了矢量化带来的任何效率收益。

%timeit a = np.array([2,2,2]); b=np.array([1,1,1])
1.55 µs ± 54.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

a = np.array([2,2,2])
b = np.array([1,1,1])
%timeit a - b
417 ns ± 12.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

use a for loop使用 for 循环

a = [3,5,6]
b = [3,7,2]

c = []

for i in range(len(a)):
     c.append(a[i] - b[i])

print(c)

output [0, -2, 4]输出 [0, -2, 4]

Very easy好简单

list1=[1,2,3,4,5]
list2=[1,2]
list3=[]
# print(list1-list2)

for element in list1:
    if element not in list2:
       list3.append(element)

print(list3)

尝试这个:

list(array([1,2,3])-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM