s=[['aaa'], ['bbb'], ['ccc'], ['ddd']]
I want to merged these list together by two elements, like this:
[['aaa','bbb'],['ccc','ddd']]
Please help me. I don't now how to do this.
Thank you
s=[['aaa'], ['bbb'], ['ccc'], ['ddd']]
I want to merged these list together by two elements, like this:
[['aaa','bbb'],['ccc','ddd']]
Please help me. I don't now how to do this.
Thank you
This is a nice way to do it:
s_even = s[0::2]
s_odd = s[1::2]
merged = zip(s_even,s_odd)
Or a short version:
merged = zip(s[0::2], s[1::2])
to get your exact format (list instead of tuple, flat list used):
# flatten list (NOTE: there are *way* more efficient ways)
s = sum(s, [])
# merge using same concept as above
merged = map(list, zip(s[0::2], s[1::2]))
You can use map
with lambda
s=[['aaa'], ['bbb'], ['ccc'], ['ddd']]
res= map(lambda i:s[i]+s[i+1], range(0, len(s)-1, 2))
print res
Output:
[['aaa', 'bbb'], ['ccc', 'ddd']]
You can use the range
function that has the syntax range(start, stop, step)
. If you step 2 elements at a time, you can use a list comprehension to append the pairs of sublists.
>>> [s[i] + s[i+1] for i in range(0, len(s), 2)]
[['aaa', 'bbb'], ['ccc', 'ddd']]
In [1]: s=[['aaa'], ['bbb'], ['ccc'], ['ddd']]
In [2]: [ [ s[i*2][0], s[i*2 + 1][0] ] for i in range(len(s)/2) ]
Out[2]: [['aaa', 'bbb'], ['ccc', 'ddd']]
In [3]: