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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
nutship
  • 4,624
  • 13
  • 47
  • 64

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
  • 244,495
  • 58
  • 464
  • 504
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
  • 18,415
  • 4
  • 40
  • 50