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