可能重复:
How do you split a list into evenly sized chunks in Python?
我有一个list
,例如:
L = [1,2,3,4,5,6,7,8]
假设我想将此L
分为3部分,如:
result = [[1,2,3],[4,5,6],[7,8]]
如果不使用更高级的编程方法(仅使用简单的PYTHON方法),我该怎么做?
答案 0 :(得分:1)
您可以尝试以下内容:
In [13]: l = [1,2,3,4,5,6,7,8]
In [14]: result = [l[i:i+3] for i in xrange(0, len(l), 3)]
In [15]: result
Out[15]: [[1, 2, 3], [4, 5, 6], [7, 8]]
这会从列表中提取长度为n
的切片,其中n
是您添加到i
的数字,也是range
中的步长值}。正如@Eric指出的那样,这会将列表分成三个块,而不是三个块。为了将它分成三个块,您可以执行以下操作:
In [21]: l = [1,2,3,4,5,6,7,8]
In [22]: chunk = int(round(len(l)/3.0))
In [23]: result = [l[i:i+chunk] for i in range(0,len(l),chunk)]
In [24]: result
Out[24]: [[1, 2, 3], [4, 5, 6], [7, 8]]
In [25]: l = [1,2,3,4,5]
In [26]: chunk = int(round(len(l)/3.0))
In [27]: result = [l[i:i+chunk] for i in range(0,len(l),chunk)]
In [28]: result
Out[28]: [[1, 2], [3, 4], [5]]
听起来你有某些约束,这也可以用for
循环编写(虽然这实际上有比上面那个更多的函数调用:)):
In [17]: result = []
In [18]: for i in xrange(0, len(l), 3):
....: result.append(l[i:i+3])
....:
....:
In [19]: result
Out[19]: [[1, 2, 3], [4, 5, 6], [7, 8]]
答案 1 :(得分:1)
RocketDonkey的答案应该没问题。这是没有列表理解的那个:
l = [1,2,3,4,5,6,7,8]
result = {}
idx = 0
for i in l:
group = idx/3
if group not in result:
result[group] = []
result[group].append(i)
idx += 1
result.values()
>>> [[1, 2, 3], [4, 5, 6], [7, 8]]
enumerate()
可用于删除手动idx增量。