因此,问题表明我必须执行以下操作:
编写从用户获取非空整数列表的代码,以及宽度。返回一个新列表,其中原始列表已转换为具有指定宽度的二维列表,根据需要在末尾填充零。除了len()和.append()之外,您不能使用任何内置函数/方法。
我试图解决它,我仍然挂在一条线上,他就是我现在所拥有的:
def chop(l1, w):
list1 = l1
width = w
list2 = []
size = len(list1)
i = 0
j = 0
k = 0
a = width - size % width
while i < a:
list1.append(0)
i = i + 1
i = 0
size = size + a
height = size // width
k = 0
while i < height:
while j < width:
list2[i][j] = list1[k]
k = k + 1
j = j + 1
j = 0
i = i + 1
return list1
但是当我尝试运行代码时,我在这行代码中遇到错误:list2[i][j] = list1[k]
给我一个索引错误。
答案 0 :(得分:1)
这里是代码(注意它看起来好多了 - 而且更短 - 因为 Python 有很多(强大的)功能,但是由于强加的限制,这就是结果):
def chop(initial_list, width):
if width <= 0:
return None
ret_list = []
size = len(initial_list)
height = size // width
i = 0
j = 0
while i < height: # Handling the integral (complete/full) rows (if any)
tmp_list = []
j = 0
while j < width:
tmp_list.append(initial_list[i * width + j])
j += 1
ret_list.append(tmp_list)
i += 1
remainder = size % width
tmp_list = []
if remainder: # Handling the last(incomplete) row (if any)
j = i * width
while j < size: # Fill the last row with the last elements from initial_list
tmp_list.append(initial_list[j])
j += 1
j = remainder
while j < width: # Append 0s till the last row length is equal to width
tmp_list.append(0)
j += 1
ret_list.append(tmp_list)
elif not height: # Handle empty list's case
j = 0
while j < width:
tmp_list.append(0)
j += 1
ret_list.append(tmp_list)
return ret_list
if __name__ == "__main__":
# Test our function a little bit...
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(chop(l1, 2))
print(chop(l1, 3))
print(chop(l1, 12))
print(chop(l1, 1))
print(chop([], 4))
print(chop([], 0))
输出是:
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0]] [[1], [2], [3], [4], [5], [6], [7], [8], [9]] [[0, 0, 0, 0]] None
@ EDIT0 :添加了对空列表的支持。