【问题标题】:Array: add an ID value in a new column when two rows (in different arrays) are equals数组:当两行(在不同数组中)相等时,在新列中添加一个 ID 值
【发布时间】:2021-11-27 17:04:10
【问题描述】:

我是 python 的初学者。 我有 2 个包含 3 列的数组(ID、X_coord、Y_coord)。 在这两个数组中,点的 x 和 y 与不同的 ID 相关。 我的目标是添加一列并将相同的 ID 分配给相同的点。

假设我们有:

a = [[1, 4500, 5000], [2, 4600, 5100], [3, 4700, 5200]]
b = [[3, 4500, 5000], [1, 4600, 5100], [2, 4700, 5200]]

我想获得类似的东西:

a_new = [[1, 1, 4500, 5000], [2, 2, 4600, 5100], [3, 3, 4700, 5200]]
b_new = [[3, 1, 4500, 5000], [1, 2, 4600, 5100], [2, 3, 4700, 5200]]

我不知道如何实现这个问题。 我正在考虑根据 x 和 y 坐标对行进行排序,但我更愿意为每一行设置一个 for 和 when 循环,当第二行和第三行中的值相同时,设置(在第四列)一个递增的值。

希望我对问题的解释是详尽无遗的。

【问题讨论】:

  • 这些真的是arrays吗?还是您的意思是列表?

标签: python arrays loops sorting for-loop


【解决方案1】:

我希望我正确理解了您的问题。要添加第一次出现的 ID 为 (X, Y) 的新列,您可以这样做:

a = [[1, 4500, 5000], [2, 4600, 5100], [3, 4700, 5200]]
b = [[3, 4500, 5000], [1, 4600, 5100], [2, 4700, 5200]]

# create a temporary dictionary with IDs:
tmp = {}
for id_, x, y in a:
    tmp[(x, y)] = tmp.get((x, y), id_)

# add new column to a and b
a = [[id_, tmp[(x, y)], x, y] for id_, x, y in a]
b = [[id_, tmp[(x, y)], x, y] for id_, x, y in b]

print(a)
print(b)

打印:

[[1, 1, 4500, 5000], [2, 2, 4600, 5100], [3, 3, 4700, 5200]]
[[3, 1, 4500, 5000], [1, 2, 4600, 5100], [2, 3, 4700, 5200]]

【讨论】:

  • 你说得对!非常感谢
  • 好的,那么如果x和y位置的值不完全相同,但它们有细微的差别,代码会发生什么变化?例如:a = [[1, 4500, 5000], [2, 4600, 5100], [3, 4700, 5200]] b = [[3, 4505, 4989], [1, 4620, 5140], [ 2, 4680, 5123]] 结果:a = [[1, 1, 4500, 5000], [2, 2, 4600, 5100], [3, 3, 4700, 5200]] b = [[3, 1 4505, 4989], [1, 2, 4620, 5140], [2, 3, 4680, 5123]]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 2023-02-08
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多