问题描述
有人可能会想弄平列表列表,:我想知道如何将平面列表转换为列表列表.
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
How does zip(*[iter(s)]*n)
work
这篇关于将平面列表转换为python中的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!