我有一个包含奇数个元素的列表。我想把它转换成特定的尺寸。我的代码:alist = ['a','b','c']cols= 2rows = int(len(alist)/cols)+1 # 2anarray = np.array(alist.extend([np.nan]*((rows*cols)-len(months_list)))).reshape(rows,cols)当前输出:ValueError: cannot reshape array of size 1 into shape (2,2)预期输出:anarray = [['a','b'],['c',nan]]
3 回答
翻翻过去那场雪
TA贡献2065条经验 获得超13个赞
你可以试试:
out = np.full((rows,cols), np.nan, dtype='object') out.ravel()[:len(alist)] = alist
输出:
array([['a', 'b'], ['c', nan]], dtype=object)
作为旁注,这可能对您更好:
rows = int(np.ceil(len(alist)/cols))
Qyouu
TA贡献1786条经验 获得超11个赞
尝试(没有任何外部库)
import math
alist = ['a', 'b', 'c']
cols = 2
new_list = []
steps = math.ceil(len(alist) / cols)
start = 0
for x in range(0, steps):
new_list.append(alist[x * cols: (x + 1) * cols])
new_list[-1].extend([None for t in range(cols - len(new_list[-1]))])
print(new_list)
输出
[['a', 'b'], ['c', None]]
holdtom
TA贡献1805条经验 获得超10个赞
您可以使用列表理解来实现结果:
li = ['a','b','c']
l = len(li)
new_list = [li[x:x+2] for x in range(l // 2)]
if l % 2 != 0:
new_list.append([li[-1], None])
print(new_list) # [['a', 'b'], ['c', None]]
添加回答
举报
0/150
提交
取消