【发布时间】:2019-10-26 14:28:22
【问题描述】:
如何转换
list = [a, b, c, d, e, f, g, h, i]
到这里
list = [[a, b, c], [d, e, f], [g, h, i]]
我想将对象分成三组。
【问题讨论】:
标签: python arrays python-3.x list if-statement
如何转换
list = [a, b, c, d, e, f, g, h, i]
到这里
list = [[a, b, c], [d, e, f], [g, h, i]]
我想将对象分成三组。
【问题讨论】:
标签: python arrays python-3.x list if-statement
此函数应将任何列表分成三部分。
def chunks(l):
return [l[i:i + 3] for i in range(0, len(l), 3)]
如果你想要更长的版本,你可以。
def chunks(l):
result = []
for i in range(0, len(l), 3):
result.append(l[i:i + 3])
return result
【讨论】:
使用 numpy reshape 函数,如下:
import numpy as np
l = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'])
l.reshape(3,3)
【讨论】:
与@Ian 相同,但将其列出以回答问题
initial_state = [1,2,0,3,4,5,6,7,8]
l = np.array(initial_state)
ilist = l.reshape(3,3).tolist()
print(ilist)
[[1, 2, 0], [3, 4, 5], [6, 7, 8]]
【讨论】: