1

Given this nested list:

nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']]

I'd like to join every 3 elements of nested_lst[1] for the result of:

nested_lst = [u'Tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]]
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
nutship
  • 4,314
  • 12
  • 46
  • 60

2 Answers2

4

Use a list comprehension:

>>> nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']]
>>> x=nested_lst[1]

>>> nested_lst[1]=[ tuple(x[i:i+3]) for i in xrange(0,len(x),3) ]
>>> nested_lst
[u'Tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]]

or you can also use itertools.islice:

>>> from itertools import islice
>>> nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']]
>>> x=nested_lst[1]
>>> it=iter(x)

>>> nested_lst[1]=[tuple( islice(it,3) ) for i in xrange(len(x)/3)]
>>> nested_lst
[u'Tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
2

Typically you'd use a list comprehension like @AshwiniChaudhary has posted, but here's an alternate solution using this technique

>>> nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']]
>>> [nested_lst[0], zip(*[iter(nested_lst[1])]*3)]
[u'Tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]]
Community
  • 1
  • 1
Nolen Royalty
  • 17,717
  • 4
  • 38
  • 48