0

编辑:感谢您的回复,这些回复很有帮助,但我不确定他们是否解决了我的问题的核心。在某些情况下,简单地选择列表中较低的值然后相应地添加值会很好,但在这种情况下,我实际上希望将不均匀列表视为较短的列表对于它缺失的值具有零值。所以我希望 [1, 2, 3] + [1, 2] 起到 [1, 2, 3] + [1, 2, 0] 的作用。我不认为 zip 或反转我的运营商会实现这一点。

我正在尝试创建一个函数,该函数添加两个列表的相应值并返回一个新列表,其中包含两个原始列表的每个索引的总和:

def addVectors(v1, v2):
    print(v1[0], v1[1], v2[0])
    newVector = []
    if len(v1) > len(v2):
        for index in range(len(v1)):
            print(index)
            newVector[index] += v1[index] + v2[index]
    else:
        for index in range(len(v2)):
            print(index)
            newVector[index] += v2[index] + v1[index]
    return newVector


addVectors([1, 2, 3], [1, 2])

但是我收到一个错误,指出列表索引超出范围?不知道我在这个看似简单的程序中做错了什么......

4

7 回答 7

7

您可能打算更改线路:

if len(v1) > len(v2):

到:

if len(v1) < len(v2):

这样,当 v1 较短时,您将迭代到 v1 中的元素数量,这可以防止您越过边缘。

请注意,这也会引发错误,因为newVector它是一个长度为 0 的列表,并且您正在访问其范围之外。你必须改变

newVector[index] += v1[index] + v2[index]

newVector.append(v1[index] + v2[index])

但是,请注意,这可以更简单地完成如下所示:

def addVectors(v1, v2):
    return map(sum, zip(v1, v2))

ETA:要用零填充列表,请执行以下操作:

import itertools
def addVectors(v1, v2):
    return map(sum, itertools.izip_longest(v1, v2, fillvalue=0))

例如:

addVectors([1, 2, 3, 4, 5], [1, 2])
# [2, 4, 3, 4, 5]
于 2012-09-20T21:12:14.733 回答
4

为什么不直接使用这个?

def sum_lists(a, b):
    return [x[0] + x[1] for x in zip(a, b)]

sum_lists([1, 2, 3], [4, 5, 6])    # -> [5, 7, 9]
于 2012-09-20T21:12:44.670 回答
2

您比较列表的长度,这是正确的。但是随后您更改了所需的操作。即当 list1 比 list2 长时,您应该只循环遍历list2长度的元素。

于 2012-09-20T21:13:15.293 回答
2

要填充长度不等的列表,您可以使用itertools

>>> import itertools
>>> map(sum, itertools.izip_longest([1,2,3], [1,2], fillvalue = 0))
[2, 4, 3]
于 2012-09-20T21:29:04.037 回答
1

你的问题出在这里:

if len(v1) > len(v2):
    for index in range(len(v1)):
        print(index)
        newVector[index] += v1[index] + v2[index]

您确保len(v1) > len(v2),但随后迭代range(len(v1))

在您的示例中,您尝试访问v2[2]不存在的 。

更新:

作为对您的编辑的回应,您可以使用以下内容:

def addVectors(v1, v2):
    if len(v1) > len(v2):
        map(sum, zip(v1, v2)).extend(v1[len(v2):])
    else:
        map(sum, zip(v1, v2)).extend(v2[len(v1):])
于 2012-09-20T21:14:19.210 回答
0

您的 IndexError 是因为当 newVector 是一个空列表时您正在尝试写入 newVector[index] 。您需要将其初始化为一堆零,或者使用 append 代替。

>>> first = [1,2,3]
>>> second = [1,2]
>>> output = []
>>> for i, item in enumerate(first):
...   additional = second[i] if i < len(second) else 0
...   output.append(item + additional)
...
>>> output
[2, 4, 3]

为了确保 len(first) > len(second),您可以执行以下操作:

first, second = first, second if len(first) > len(second) else second, first
于 2012-09-20T22:00:57.050 回答
0

或者你可以试试

def add_vector(vector1, vector2):
index = len(vector1) - 1
new = []
while index >= 0:
    result = vector1[index] + vector2[index]
    new.append(result)
    index -=1
new.reverse()
return new
于 2020-06-14T06:09:14.373 回答