添加多个列表

时间:2014-06-09 12:53:05

标签: python

我想尝试python功能的很多方法 所以,我想不使用zip使用其他python函数,我该怎么做?

这是使用zip并添加多个列表: 但我想以其他方式不使用zip:

x = [12, 22, 32, 42, 52, 62, 72, 82, 29]
y = [10, 11, 12, 13, 14, 15, 16, 17, 18]

def add_list(i, j):
    l = []
    for n, m in zip(x, y):
        l.append(n + m)
    return l

我知道这一点,

2 个答案:

答案 0 :(得分:1)

没有使用zip,您可以使用map

from operator import add

x = [12, 22, 32, 42, 52, 62, 72, 82, 29]
y = [10, 11, 12, 13, 14, 15, 16, 17, 18]
res = map(add, x, y)
# [22, 33, 44, 55, 66, 77, 88, 99, 47]

请注意,如果迭代的长度不同,则最短的将用None填充,这将导致TypeError中的add而不是zip截断到最短的列表。

暂且没有使用zip绝对没有错 - 我可能会将其重新编写为list-comp,例如:

[sum(items) for items in zip(x, y)]

然后这很容易扩展到zip(x, y, z, another_list)等...

答案 1 :(得分:0)

哦,有很多可能性,这里有几个:

# most simple way
res = []
for i in range(len(x)):
  res.append(x[i]+y[i])

# this is the same as
res = [x[i]+y[i] for i in range(len(x))]

# more pythonic
from operator import add
res = map(add, x, y)

# less pytonic
res = map(int.__add__, x, y)

# using numpy
import numpy as np
res = list(np.array(x) + np.array(y))

# alternatively
res = list(np.add(x, y))

# also
res = list(np.sum([x,y], axis=0))
相关问题