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')]]
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')]]
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')]]
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')]]