0

So I want to change this nested(list) lets call it X

[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]

To This nested(list) lets it Y

[['What if', 'Thing Explainer', 'Alan Turing: The Enigma'], [ 2014,2015,2014], ['Randall Munroe, Randall Munroe, 'Andrew Hodges']]

The first term in Y is the first item in the ith term in X.

['What if', 'Thing Explainer', 'Alan Turing: The Enigma']

The second term in Y is the second item in the ith term in X

['Randall Munroe, Randall Munroe, 'Andrew Hodges']

Can anyone share there thought process and solutions in python?

1
  • map(list, zip(*X))
    – Amadan
    Dec 1, 2015 at 4:07

3 Answers 3

1

You will want to use the built-in zip function in Python.

>>> zip(*[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']])

There is more documentation located at https://docs.python.org/3/library/functions.html#zip

2
  • You would need to unpack the arguments to the zip function i.e. zip(*your_list).
    – AKS
    Dec 1, 2015 at 4:44
  • Yeah, I still want to return a nested loop Dec 1, 2015 at 5:04
0
map (list, zip(*[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]))

This will do you exactly what you need.

2
  • But I want a nested listed returned if I do it your way this happens a = map (list, zip(*[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']])) print(a) <map object at 0x101e0f438> Dec 1, 2015 at 16:08
  • 1
    Just converted it to list object, thank you !!! Dec 1, 2015 at 16:24
0

I'm not sure what packages you want to/don't want to use. But numpy can do this quite easily:

import numpy as np
dat = [['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]
np.array(dat).T.tolist()
# [['What if?', 'Thing Explainer', 'Alan Turing: The Enigma'],
#  [' 2014', ' 2015', ' 2014'],
#  [' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']]
1
  • Sorry can't import anything :S Dec 1, 2015 at 5:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.