python - Merging some elements inside a list -


given nested list:

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

i'd join every 3 elements of nested_lst[1] result of:

nested_lst = [u'tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]] 

use 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]) in xrange(0,len(x),3) ] >>> nested_lst [u'tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]] 

or can use itertools.islice:

>>> 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) ) in xrange(len(x)/3)] >>> nested_lst [u'tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]] 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -