将平面列表转换为python中的列表列表

Oz1*_*123 21 python list

通常情况下,你想要反过来,就像这里一样.我想知道你如何将一个平面列表转换为一个列表,在python中的quasy重塑数组

在numpy你可以做类似的事情:

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

我想知道你是如何做相反的事情,我通常的解决方案是这样的:

>>> 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']]
Run Code Online (Sandbox Code Playgroud)

是否有更"Pythonic"的方式来做到这一点?

jam*_*lak 36

>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd'), ('e', 'f')]
Run Code Online (Sandbox Code Playgroud)

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

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

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

zip(*[iter(s)]*n)工作怎么样

  • 此解决方案仅在有足够的项目填充时才有效,否则项目将被切断. (3认同)
  • 要生成一个列表列表:`map(list,zip(*[iter(l)]*2))`,或`map(list,zip(*[iter(l)]*3))`等. (2认同)

Sve*_*ach 13

这通常使用itertools文档中的石斑鱼配方完成:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)

例:

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> list(grouper(2, my_list))
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', None)]
Run Code Online (Sandbox Code Playgroud)


Rya*_*n M 8

创建列表列表的另一种方法可以简化,如下所示:

>>>MyList = ['a','b','c','d','e','f']
# Calculate desired row/col
>>>row = 3
>>>col = 2
>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
>>>NewList
[['a', 'b', 'c'], ['d', 'e', 'f']]
Run Code Online (Sandbox Code Playgroud)

这种方法可以扩展为产生任何行和列大小.如果选择行和列值row*col >len(MyList),那么包含最后一个值的子列表(行)MyList将在那里结束,并且NewList将简单地填充适当数量的空列表以满足行/列规范

>>>MyList = ['a','b','c','d','e','f','g','h']
>>>row = 3
>>>col = 3
>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
>>>NewList
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]

>>>row = 4
>>>col = 4
>>>NewList = [MyList[col*i : col*(i+1)] for i in range(row)]
[['a', 'b', 'c', 'd'], ['e', 'f', 'g','h'], [], []]
Run Code Online (Sandbox Code Playgroud)

  • 我想这应该是接受的答案,因为问题是要求列表而不是元组列表.或罗伯特在上述评论中的回答. (3认同)