尝试进行交错,但因为我是初学者而遇到麻烦。 它假设在测试时交错整数集,但我只是不断收到一条错误消息,说明"索引超出范围"。
def interleave(nums):
new_nums = []
index = 0
if len(nums) == 0:
return new_nums
for j in range(len(nums)):
for i in range(len(nums[0])):
new_nums.append(nums[j][index])
index += 1
return new_nums
并使用以下值进行测试:
print("Testing interleave() for nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]: " + str(
interleave([[1, 2, 3], [4, 5, 6], [7, 8, 9]])))
预期结果是:
[1, 4, 7, 2, 5, 8, 3, 6, 9]
使用这两个值进行测试时:
print("Testing interleave() for nums = [[0, 1, 0], [1, 0, 0], [0, 0, 1]]: " + str(
interleave([[0, 1, 0], [1, 0, 0], [0, 0, 1]])))
print("Testing interleave() for nums = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]: " + str(
interleave([[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]])))
预期结果应为:
[0, 1, 0, 1, 0, 0, 0, 0, 1]
[1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
但是我得到一个IndexError:list index超出范围
答案 0 :(得分:0)
简单修复您的功能
def interleave(nums):
new_nums = []
index = 0
if len(nums) == 0:
return new_nums
for j in range(len(nums)):
for i in range(len(nums[0])):
new_nums.append(nums[i][index])
index += 1
return new_nums
print("Testing interleave() for nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]: " + str(
interleave([[1, 2, 3], [4, 5, 6], [7, 8, 9]])))
您可以使用j而不是索引 - 不需要索引
基本上,你要做的是转置二维数组和ravel(concat) 使用numpy
参见下面的最后一行import numpy as np
def interleave(nums):
new_nums = []
if len(nums) == 0:
return new_nums
for j in range(len(nums)):
for i in range(len(nums[0])):
new_nums.append(nums[i][j])
return new_nums
print("Testing interleave() for nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]: " + str(
interleave([[1, 2, 3], [4, 5, 6], [7, 8, 9]])))
print ("Testing interleave() for nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]: ", list(np.ravel(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).transpose())))
答案 1 :(得分:0)
此处的问题是index
永远不会重置,因此您获得的最大值为index
,这是您拥有的元组数量。
如果你反过来说,你可能会发现它更容易,首先你循环遍历单个元组元素,然后遍历元组列表。这样你也可以摆脱index
:
def interleave(nums):
new_nums = []
if len(nums) == 0:
return new_nums
for j in range(len(nums[0])):
for i in range(len(nums)):
new_nums.append(nums[i][j])
return new_nums
print("Testing interleave() for nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]: " + str(
interleave([[1, 2, 3], [4, 5, 6], [7, 8, 9]])))