且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-23 10:45:14

>>> 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