Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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 3.x 如何用n个项目的列表制作列表_Python 3.x_List_For Loop - Fatal编程技术网

Python 3.x 如何用n个项目的列表制作列表

Python 3.x 如何用n个项目的列表制作列表,python-3.x,list,for-loop,Python 3.x,List,For Loop,我有一张单子 ['Boogeyman', '66', 'Battleground', '50', 'Rodgeners', '17'] 我想要一个包含n个(例如2个)元素的列表,即 [['Boogeyman', '66'],['Battleground', '50'],['Rodgeners', '17']] 它是怎么用的 In [1]: l = list(range(10)) In [2]: [l[i:i+2] for i in range(0,len(l),2)] Out[2]: [[

我有一张单子

['Boogeyman', '66', 'Battleground', '50', 'Rodgeners', '17']
我想要一个包含n个(例如2个)元素的列表,即

[['Boogeyman', '66'],['Battleground', '50'],['Rodgeners', '17']]
它是怎么用的

In [1]: l = list(range(10))

In [2]: [l[i:i+2] for i in range(0,len(l),2)]
Out[2]: [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
有一种更惯用的方法来做这件事

受itertools的启发,答案是可行的

list(zip(*([iter(range(10))] * 2)))


如评论中所述,以下列表中有
grouper


请查看中的
grouper
。请拿下,仔细阅读。请详细说明你的问题。
from itertools import zip_longest
list(zip_longest(*([iter(range(9))] * 2), fillvalue='x'))
from itertools import zip_longest


def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n

    # this will return tuples
    # return zip_longest(*args, fillvalue=fillvalue)

    # this will return lists
    return (list(item) for item in zip_longest(*args, fillvalue=fillvalue))

lst = ['Boogeyman', '66', 'Battleground', '50', 'Rodgeners', '17']
res = list(grouper(lst, 2))
# [['Boogeyman', '66'], ['Battleground', '50'], ['Rodgeners', '17']]