Reputation: 37
I have a script in Python which will parse some values from a file and will store it in a 2d lists like the below:
[['x'], ['Y'], ['Z']]
[['99'], ['88'], ['77']]
[['host1'], ['host2'], ['host3']]
[['a', 'b', 'c','d','e'], ['f, 'g', 'h','i','j'], ['k', 'l', 'm','n','o']]
All I want to achieve is to combine these lists in one large list using the following order
[[['X'],['99'],['host1'], ['a','b','c','d','e']], [['Y'], ['88'], ['host2'], ['f','g','h','i',j]]] etc ..
I have searched stackoverflow for such question and I couldn't find any.
Any help will be greatly appreciated.
Thanks
Upvotes: 0
Views: 53
Reputation: 11590
As already mentioned in the excellent answer you got, use zip
.
a=[['x'], ['Y'], ['Z']]
b=[['99'], ['88'], ['77']]
c=[['host1'], ['host2'], ['host3']]
d=[['a', 'b', 'c','d','e'], ['f', 'g', 'h','i','j'], ['k', 'l', 'm','n','o']]
z=[list(el) for el in zip(a,b,c,d)]
print z
produces
[[['x'], ['99'], ['host1'], ['a', 'b', 'c', 'd', 'e']], [['Y'], ['88'], ['host2'], ['f', 'g', 'h', 'i', 'j']], [['Z'], ['77'], ['host3'], ['k', 'l', 'm', 'n', 'o']]]
which is a list of lists, not of tuples (as indicated in the question).
There is no practical difference if all you need to do on the elements is to iterate over them and read from them. On the other hand, in case you need to alter the elements and change them 'in-place', lists allow you to do that (they are mutable), whereas tuples do not.
Upvotes: 0
Reputation: 113864
Let's define your lists:
>>> a = [['x'], ['Y'], ['Z']]
>>> b = [['99'], ['88'], ['77']]
>>> c = [['host1'], ['host2'], ['host3']]
>>> d = [['a', 'b', 'c','d','e'], ['f', 'g', 'h','i','j'], ['k', 'l', 'm','n','o']]
I believe that this does what you want:
>>> zip(a, b, c, d)
[(['x'], ['99'], ['host1'], ['a', 'b', 'c', 'd', 'e']), (['Y'], ['88'], ['host2'], ['f', 'g', 'h', 'i', 'j']), (['Z'], ['77'], ['host3'], ['k', 'l', 'm', 'n', 'o'])]
Upvotes: 3