将关键字 None 附加到列表中的子列表
Appending keyword None to sublists in lists
我想将关键字 None 添加到列表中。
- 如果输入列表中的元素个数
小于 rows*columns 然后用关键字 None.
填充二维列表
- 如果输入列表中的元素个数大于行*列
然后忽略多余的元素。
对于给定的输入 try_convert_1D_to_2D([1, 2, 3, 4], 3, 4)
我想实现这样的结果:[[1, 2, 3, 4], [None, None, None, None], [None, None, None, None]]
我试过的是:
def try_convert_1D_to_2D(my_list, r, c):
a=r*c
b=len(my_list)
if(b >= a):
l=[my_list[i:i+c] for i in range(0,b,c)]
return l[0:r]
else:
for i in range(0,b,c):
k=my_list[i:i+c]
return [k.append(None) for k in a]
为输入
try_convert_1D_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3)
我可以达到 [[8, 2, 9],[4, 1, 6]]
这是正确的。
谁能告诉我哪里做错了,请告诉我如何做最好。谢谢。
我指出 ,这是一个实际有效的版本:
def try_convert_1D_to_2D(my_list, r, c):
# Pad with Nones to necessary length
padded = my_list + [None] * max(0, (r * c - len(my_list)))
# Slice out rows at a time in a listcomp until we have what we need
return [padded[i:i+c] for i in range(0, r*c, c)]
我想将关键字 None 添加到列表中。
- 如果输入列表中的元素个数 小于 rows*columns 然后用关键字 None. 填充二维列表
- 如果输入列表中的元素个数大于行*列 然后忽略多余的元素。
对于给定的输入 try_convert_1D_to_2D([1, 2, 3, 4], 3, 4)
我想实现这样的结果:[[1, 2, 3, 4], [None, None, None, None], [None, None, None, None]]
我试过的是:
def try_convert_1D_to_2D(my_list, r, c):
a=r*c
b=len(my_list)
if(b >= a):
l=[my_list[i:i+c] for i in range(0,b,c)]
return l[0:r]
else:
for i in range(0,b,c):
k=my_list[i:i+c]
return [k.append(None) for k in a]
为输入
try_convert_1D_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3)
我可以达到 [[8, 2, 9],[4, 1, 6]]
这是正确的。
谁能告诉我哪里做错了,请告诉我如何做最好。谢谢。
我指出
def try_convert_1D_to_2D(my_list, r, c):
# Pad with Nones to necessary length
padded = my_list + [None] * max(0, (r * c - len(my_list)))
# Slice out rows at a time in a listcomp until we have what we need
return [padded[i:i+c] for i in range(0, r*c, c)]