Domanda

I am trying to merge 2 lists like so

coordinates_X = [1, 17, 9]
coordinates_Y = [3, 5, 24]

outcome = [1, 3, 17, 5, 9, 24]
È stato utile?

Soluzione

Are the lists always the same length? If so, this will give you a list of tuples:

outcome = zip(coordinates_X, coordinates_Y)

You can then flatten that:

import itertools
outcome = list(itertools.chain.from_iterable(zip(coordinates_X, coordinates_Y)))

For 2.x, itertools also has izip available, which builds an iterable yielding tuples. But that's unnecessary for lists this small. On 3.x, zip always returns an iterable.

If they're not the same length, zip or itertools.izip will truncate the outcome to match the shorter list. itertools.izip_longest can extend a shorter list with a fill value specified in the call, if you need that.

Altri suggerimenti

An alternate without itertools:

result = []
for i in zip(coordinates_X,coordinates_Y):
    result.extend(i)

** the Code you can use is: **

  coordinates_X = [1, 17, 9]
    coordinates_Y = [3, 5, 24]

    outcome =coordinates_X+coordinates_Y

If ordering isn't required, you can do:

coordinates_X + coordinates_Y

Also, you can use list comprehensions to output exactly what you

[ x for y in map(lambda x, y: [x, y], coordinates_X, coordinates_Y) for x in y ]

Probably not the best way to do it, but it was what occurred to me :).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top