Reputation: 193
I have two lists:
xy = [[1,2],[3,4],[5,6]]
z = [1,3,5]
I want to merge them to get:
xyz = [[1,2,1],[3,4,3],[5,6,5]]
or
xyz = [(1,2,1),(3,4,3),(5,6,5)]
Here is how I achieve this:
for i,lst in enumerate(xy):
lst.append(z[i])
xy
Is there any neater way to do it without using the for loop or something?
Upvotes: 0
Views: 54
Reputation: 19677
If you are using Python 3.5+, you can make use of PEP 448:
xyz = [(*a, b) for a, b in zip(xy, z)]
This also uses list comprehension and zip()
to make it a simple one-liner.
If you do not want to use a for
loop at all, there is actually a way using functional programming and map()
, but this is probably not the best way to go (Python does not favor functional programming):
xyz = map(lambda a, b: a + [b], xy, z)
Upvotes: 5
Reputation: 1141
I would suggest list-comprehensions for readability:
[a + [b] for a, b in zip(xy, z)]
Upvotes: 0
Reputation: 92854
Short list comprehension with enumerate
function:
result = [l+[z[k]] for k,l in enumerate(xy)]
print(result)
The output:
[[1, 2, 1], [3, 4, 3], [5, 6, 5]]
Upvotes: 0
Reputation: 44878
This may be a neater way:
Ret = [a + [b] for a, b in zip(xy, z)]
Upvotes: 3