在Python中,如何将一个列表中的所有整数以相同的顺序添加到另一个长度不同的列表中的整数?
鉴于:在Python中,如何将一个列表中的所有整数以相同的顺序添加到另一个长度不同的列表中的整数?,python,python-2.7,numpy,Python,Python 2.7,Numpy,鉴于: ListA=[1,2,3,4,5] ListB=[10,20,30,40,50,60,70] 我如何使它成为ListC=[11,22,33,44,55,60,70],其中C[0]=B[0]+A[0]C[5]=nil+B[5]等等?在这种情况下,我不能简单地使用for循环,因为将有一个索引器,因为ListB与ListA?相比,还有两个条目。itertools.zip\u longest(…,fillvalue=0): 如果您喜欢numpy解决方案,可以使用numpy.pad将两个列表填充到
ListA=[1,2,3,4,5]
ListB=[10,20,30,40,50,60,70]
我如何使它成为
ListC=[11,22,33,44,55,60,70]
,其中C[0]=B[0]+A[0]
C[5]=nil+B[5]
等等?在这种情况下,我不能简单地使用for循环,因为将有一个索引器,因为ListB
与ListA?
相比,还有两个条目。itertools.zip\u longest(…,fillvalue=0)
:
如果您喜欢numpy解决方案,可以使用numpy.pad
将两个列表填充到相同的长度:
import numpy as np
def add_np(A, B):
m = max(len(A), len(B))
return np.pad(A, (0, m-len(A)), 'constant') + np.pad(B, (0, m-len(B)), 'constant')
add_np(ListA, ListB)
# array([11, 22, 33, 44, 55, 60, 70])
由于您放置了numpy
标记:
C = np.array(ListB)
C[:len(ListA)] += ListA
C
# array([11, 22, 33, 44, 55, 60, 70])
如果您事先不知道哪个较短,哪个较长:
short, long_ = sorted([ListA, ListB], key=len)
C = np.array(long_)
C[:len(short)] += short
可以使用for循环,但必须考虑列表长度的差异。添加一条if语句,检查[5]或其他位置是否存在元素:
`
i = 0
for i in range(len(B)):
if A[i]:
C[i] = A[i] + B[i]
else:
C[i] = B[i]
`
请记住,只要在最长的列表上运行for循环,这只在您想要的意义上起作用。您可以使用以下方法:
def zip_lists(l1, l2):
if len(l1) == len(l2):
return [x + y for x, y in zip(l1, l2)]
s, b = min(l1, l2), max(l1, l2)
rest = len(s)
return [x + y for x, y in zip(s, b)] + b[rest:]
以上逻辑:
- 如果两个列表的长度相同,通常只需
zip()
- 否则,查找最小的列表
s
,以及最大的列表b
- 计算
s
的长度,即rest
- 然后从两个列表中选择
zip()
,并添加后面的元素,rest
从较大的列表中选择b
李>
zip\u list()
的行为如下所示:
>>> print(zip_lists([1,2,3,4,5], [10,20,30,40,50,60,70]))
[11, 22, 33, 44, 55, 60, 70]
>>> print(zip_lists([1,2,3,4,5], [10,20,30,40,50]))
[11, 22, 33, 44, 55]
您可以尝试以下方法:
首先添加正在配对的元素,然后添加剩余的项目:
ListA = [1,2,3,4,5]
ListB = [10,20,30,40,50,60,70]
your_data=list(map(lambda x,y:x+y,ListA,ListB))
your_data.extend(ListB[len(ListA):])
print(your_data)
输出:
[11, 22, 33, 44, 55, 60, 70]
您可以使用切片操作符
op = sum
len_a, len_b = len(ListA), len(ListB)
min_len, max_len = min(len_a,len_b), max(len_a,len_b)
ListC = list(map(op,zip(ListA[:min_len],ListB[:min_len]))) + ListA[min_len:max_len] + ListB[min_len:max_len]
最后一行将连接两个列表的其余部分。
如果它们的长度相同,那么它就不会起任何作用。
如果它们的长度不同,那么列表较小[min\u len:max\u len]
将是一个空列表:[]
因为这个问题被标记为python 2.7
,您应该更新答案,使用izip\u longest
而不是zip\u longest
op = sum
len_a, len_b = len(ListA), len(ListB)
min_len, max_len = min(len_a,len_b), max(len_a,len_b)
ListC = list(map(op,zip(ListA[:min_len],ListB[:min_len]))) + ListA[min_len:max_len] + ListB[min_len:max_len]