如何用n个项目组成一个列表

时间:2019-03-31 14:22:33

标签: python-3.x list for-loop

我有清单

['Boogeyman', '66', 'Battleground', '50', 'Rodgeners', '17']

我想获取包含n个元素(例如2个)的列表,即

[['Boogeyman', '66'],['Battleground', '50'],['Rodgeners', '17']]

它如何用于???

2 个答案:

答案 0 :(得分:1)

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

from itertools import zip_longest
list(zip_longest(*([iter(range(9))] * 2), fillvalue='x'))

答案 1 :(得分:0)

如评论中所述,itertools recipes中有grouper

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