使用zip
和列表理解:
>>> a[:] = [[x, z] for (x, y), z in zip(a, b)]
>>> a
[[10, 1], [12, 2], [13, -30], [2, 404]]
对于不等长列表的情况,您可以使用iterools.izip_longest
:
>>> from itertools import izip_longest
>>> a = [[10, 0], [12,1], [13, 8], [2, -3]]
>>> b = [10, 20]
>>> sen = object()
#len(a) > len(b)
>>> a[:] = [[x, y if z is sen else z]
for (x, y), z in izip_longest(a, b, fillvalue=sen)]
>>> a
[[10, 10], [12, 20], [13, 8], [2, -3]]
>>> a = [[10, 0], [12,1]]
>>> b = [100, 200, -30, 404]
#len(b) > len(a)
>>> a[:] = [[None if x is sen else x , z]
for (x, y), z in izip_longest(a, b, fillvalue=[sen]*2)]
>>> a
[[10, 100], [12, 200], [None, -30], [None, 404]]
generator function
如果您认为列表推导太难以理解,请使用 a :
def solve(a, b):
sen = object()
if len(a) == len(b):
for (x, y), z in zip(a, b):
yield [x, z]
elif len(a) > len(b):
for (x, y), z in izip_longest(a, b, fillvalue=sen):
yield [x, y if z is sen else z]
else:
for (x, y), z in izip_longest(a, b, fillvalue=[sen]*2):
yield [None if x is sen else x , z]
演示:
>>> list(solve([[10, 0], [12,1], [13, 8], [2, -3]], [1, 2, -30, 404]))
[[10, 1], [12, 2], [13, -30], [2, 404]]
>>> list(solve([[10, 0], [12,1], [13, 8], [2, -3]], [10, 20]))
[[10, 10], [12, 20], [13, 8], [2, -3]]
>>> list(solve([[10, 0], [12,1]], [100, 200, -30, 404]))
[[10, 100], [12, 200], [None, -30], [None, 404]]