gpt4 book ai didi

python - 如何按正确的列位置重新排序字段?

转载 作者:行者123 更新时间:2023-12-05 01:51:09 25 4
gpt4 key购买 nike

有一个正确位置的表头:

arr = [1,2,3,4,5,6]

还有一个矩阵(rowsxcols):

matrix = [
[2,3,4],
[1,3,6],
[2,4,5]]

我尝试创建一个新矩阵,其中矩阵的所有元素都在arr的正确位置。结果我想得到这个矩阵:

new_matrix = [[0,2,3,4,0,0],
[1,0,3,0,0,6],
[0,2,0,4,5,0]

我的完整代码是:

arr = [1,2,3,4,5,6]
matrix = [
[2,3,4],
[1,3,6],
[2,4,5]]
rows = len(matrix)
summator = {}
positions = {}

for i in range(rows):
cols = len(matrix[i])

if i > 0:
matrix[i] = matrix[i] + [0] * (len(matrix[i - 1]) - cols);

for j in range(cols):
if j not in summator:
summator[j] = matrix[i][j]
else:
summator[j] += matrix[i][j]

positions[j] = (summator[j] == (j + 1) * rows)


new_matrix = [[]]

for i in range(rows):
row = []
cols = len(matrix[i])

for j in range(cols):
if j in positions and positions[j] == True:
row.insert(j, matrix[i][j])
continue

columnHeaderValue = arr[j]
columnValue = matrix[i][j]
diff = columnValue - columnHeaderValue

if diff > 0:
print("Move right: " + str(matrix[i][j]))
row.insert(j, 0)
row.insert(j + 1, matrix[i][j])
new_matrix.append(row)

print(new_matrix)

我在尝试创建新矩阵时遇到问题:

new_matrix = [[]]

最佳答案

您可以使用简单的列表理解来解决这个问题:

sets = [set(l) for l in matrix]
# [{2, 3, 4}, {1, 3, 6}, {2, 4, 5}]

new_matrix = [[e if e in s else 0 for e in arr] for s in sets]

注意。为了提高效率,我首先将矩阵转换为集合(in 运算符对于集合来说是 O(1),对于列表来说是 O(n))。您可以使用 matrix 代替 sets,它会起作用,只是效率较低。

输出:

[[0, 2, 3, 4, 0, 0],
[1, 0, 3, 0, 0, 6],
[0, 2, 0, 4, 5, 0]]

关于python - 如何按正确的列位置重新排序字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72481149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com