0

Let's say I have a list like this:

rows=[['a1','a3','a5','a7'], ['a2','a4','a6','a8']]

And I want to create new list from this, so it would look like this: ['a','1','a','2','a','3'....] and so on until 'a8' in this order, but I don't want to sort the list in any way.

My point is I want to append the values in such a way that it appends first item from first list in rows, then it appends the first item from the second list, and then goes back to the second item from the first list, and so on.

How can I do that?

1
  • I think your explanation suggests you want ['a1', 'a2', 'a3', 'a4' ...] as result, but your example is different ... what do you want to achieve? Commented Apr 3, 2017 at 21:58

2 Answers 2

3

You can use zip, and then join and unwrap the items with a nested for in a list comprehension:

>>> [x for i, j in zip(*rows) for x in i+j]
['a', '1', 'a', '2', 'a', '3', 'a', '4', 'a', '5', 'a', '6', 'a', '7', 'a', '8']

You can handle lists with varying number of sublists if you collect all the items from zip in a tuple and then use str.join:

>>> [x for i in zip(*rows) for x in ''.join(i)]
['a', '1', 'a', '2', 'a', '3', 'a', '4', 'a', '5', 'a', '6', 'a', '7', 'a', '8']
Sign up to request clarification or add additional context in comments.

Comments

1

Use a list comprehension with a nested iteration:

merged = [rows[i][j] for j in len(rows) for i in len(rows[0]]

From there, I expect that you can re-cast your two-character list into the sequence of characters you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.