0
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

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Celjan
  • 17
  • 2
  • possible duplicate of [Alternative way to split a list into groups of n](http://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n) – sshashank124 Nov 08 '14 at 20:32

4 Answers4

3

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]))
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
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']]
1

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']]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • You'll face a little problem with this solution. if the length of S is odd, you will have problem 'IndexError: list index out of range'. items' index is 0->len(S)-1, so it should be: range(0, len(s)-1, 2) or s[0::2]/s[0::1] as has pointed in other answers. – user3378649 Nov 08 '14 at 13:57
  • @user3378649 The OP didn't specify how to handle odd length lists. Your suggestion may not be the desired behavior in that case. – Cory Kramer Nov 08 '14 at 14:01
0
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]:

Check Python List Comprehension

sathyz
  • 1,401
  • 10
  • 12