i have a list of lists corresponding to an array (each list inside the list has the same number of entries):
a = [[1,2,3],[4,5,6],[7,8,9]]
i'd like to convert this to a single string:
"1,4,7\t2,4,8\t3,6,9"
ie make each column be a comma separated list of string values from a. my solution with numpy arrays is quite a hack:
b = array(b)
l = len(a)
result = "\t".join([",".join(map(str, b[:,r])) for r in range(l)])
is there a more elegant way to do this? thank you.
You can transpose a list of lists using zip():
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Everything else is simple:
>>> "\t".join(",".join(map(str, r)) for r in zip(*a))
'1,4,7\t2,5,8\t3,6,9'
Use zip() function to get
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>
and than do your thing.
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> b = zip(*a)
>>> result = "\t".join([",".join(map(str, r)) for r in b])
>>> result
'1,4,7\t2,5,8\t3,6,9'
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With