-2

Hopefully I can explain this well I have a list that is n in length but for this example lets use this.

List = [[['a','b','c'], [1,2,3], [7,8,9]],[['e','f','g'], [4,5,6], [1,2,3]]]

I want to change up all the values to yield

List = [[['a',1,7], ['b',2,8], ['c',3,9]], [['f',4,1], ['g',5,2], ['c',6,3]]]

so essentially List[0][0], List[1][0], List[2][0] and so on. I have tried a bunch of stuff and I cant quite find the write mix to get this working. any help would be appreciated

I have attempted too many things to count and non of them are particularly valuable so ill leave that out for now.

3
  • What happened to "f" and "g"? Or is this a typo/copy-paste-error? Commented Jan 27, 2016 at 21:29
  • You can use numpy: import numpy as np; print([b.T for b in np.array([[['a','b','c'], [1,2,3], [7,8,9]],[['e','f','g'], [4,5,6], [1,2,3]]])]) Commented Jan 27, 2016 at 21:35
  • it was a typo! and numpy is rocking its socks off! Commented Jan 27, 2016 at 21:39

1 Answer 1

2

Use zip!

[[list(x) for x in zip(*sublist)] for sublist in List ]

Or, with unequal lengths:

[map(None, *sublist) for sublist in List] # Python 2
[list(itertools.zip_longest(*sublist)) for sublist in List] # Python 3

If you can be ensured that the sublists are of equal length and tuples would suffice instead of lists, then:

[zip(*sublist) for sublist in List]
Sign up to request clarification or add additional context in comments.

9 Comments

that works on python 2 only, me thinks
not enough. zip does not produce a list, but a tuple.
edited per above comments
OK, but do you check your code? The first line produces [['a', 1, 7], ['b', 2, 8], ['c', 3, 9], ['e', 4, 1], ['f', 5, 2], ['g', 6, 3]] on python 3
part of me knew it didn't make sense to add another for statement without another comprehension
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.