Reputation: 107
I am working on lists of list
input:
x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']]
and am looking for an output:
s = ['a_b_c_d','a_b_c_d','a_b_c_d']
Kindly let me know how can I do this using list comprehension.
Upvotes: 2
Views: 117
Reputation: 500963
In [6]: x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']]
In [7]: ['_'.join(s) for s in zip(*x)]
Out[7]: ['a_b_c_d', 'a_b_c_d', 'a_b_c_d']
As requested, this uses a list comprehension. See @eumiro's answer for a map()
-based solution that I think is just as good.
Upvotes: 11
Reputation: 213125
>>> x = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']]
>>> map('_'.join, zip(*x))
['a_b_c_d', 'a_b_c_d', 'a_b_c_d']
… although @aix's list comprehension is more list-comprehensible.
Upvotes: 12