Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并列表中的某些元素_Python_Python 2.7_List Comprehension - Fatal编程技术网

Python 合并列表中的某些元素

Python 合并列表中的某些元素,python,python-2.7,list-comprehension,Python,Python 2.7,List Comprehension,给定此嵌套列表: nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']] 我想加入嵌套的\u lst[1]的每3个元素,以获得以下结果: nested_lst = [u'Tom', [('50', ' 1.85', ' 112'), (' 60', ' 1.90', ' 115')]] 使用列表理解: >>> nested_lst = [u'Tom', ['50', ' 1.85', '

给定此嵌套列表:

nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']]
我想加入嵌套的\u lst[1]的每3个元素,以获得以下结果:

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

使用列表理解:

>>> 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')]]
或者您也可以使用
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')]]

使用列表理解:

>>> 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')]]
或者您也可以使用
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')]]

通常,您会使用@AshwiniChaudhary发布的列表理解,但这里有一个替代解决方案,使用


通常,您会使用@AshwiniChaudhary发布的列表理解,但这里有一个替代解决方案,使用


很抱歉,书籍推荐与堆栈溢出无关,它们根本不符合此处的格式。@MartijnPieters:好的,清除。。。为了清楚起见,我将删除我的答案。很抱歉,书籍推荐与堆栈溢出无关,它们根本不符合此处的格式。@MartijnPieters:好的,清楚。。。为了清楚起见,我将删除我的答案。