Turning A List Of Rows Into Columns
foo = ['123','123','123] I am attempting to turn foo into: revisedfoo = ['111', '222', '333'] This in effect is turning the 'rows' into 'columns': 111 222 333 I have attempted s
Solution 1:
With zip()
and the star operator:
>>> [''.join(i) for i in zip(*foo)]
['111', '222', '333']
Explanation
zip(*foo)
"unzips" foo, e.g.:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
So in this case:
# You need to call `list()`, because `zip()` returns
# an iterator in Python 3.x
>>> list(zip(*foo))
[('1', '1', '1'), ('2', '2', '2'), ('3', '3', '3')]
Then on each of these sub-elements (tuples), we want to join the individual elements into one string. ''.join(seq)
is the standard way to go about this.
Post a Comment for "Turning A List Of Rows Into Columns"