将平面列表转换为python中的列表列表 [英] Convert a flat list to list of lists in python

查看:85
本文介绍了将平面列表转换为python中的列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可能会想弄平列表列表,

One may want to do the contrary of flattening a list of lists, like here: I was wondering how you can convert a flat list into a list of lists.

在numpy中,您可以执行以下操作:

In numpy you could do something like:

>>> a=numpy.arange(9)
>>> a.reshape(3,3)
>>> a
array([[0, 1, 2],
   [3, 4, 5],
   [6, 7, 8]])

我想知道你是怎么做的,而我通常的解决方案是:

I was wondering how you do the opposite, and my usual solution is something like:

>>> Mylist
['a', 'b', 'c', 'd', 'e', 'f']
>>> newList = []
for i in range(0,len(Mylist),2):
...     newList.append(Mylist[i], Mylist[i+1])
>>> newList 
[['a', 'b'], ['c', 'd'], ['e', 'f']]

是否还有一种更"pythonic"的方式来做到这一点?

is there a more "pythonic" way to do it?

推荐答案

>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd'), ('e', 'f')]

正如@Lattyware指出的那样,这仅在每次zip函数的每个参数返回一个元组时,如果每个参数中都有足够的项目时才起作用.如果其中一个参数的项目少于其他参数,则将项目切掉,例如.

As it has been pointed out by @Lattyware, this only works if there are enough items in each argument to the zip function each time it returns a tuple. If one of the parameters has less items than the others, items are cut off eg.

>>> l = ['a', 'b', 'c', 'd', 'e', 'f','g']
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd'), ('e', 'f')]

如果是这种情况,那么最好使用@Sven Marnach的解决方案

If this is the case then it is best to use the solution by @Sven Marnach

zip(*[iter(s)]*n)的工作方式

How does zip(*[iter(s)]*n) work

这篇关于将平面列表转换为python中的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆