【问题标题】:Fastest way to compare Array-of-array?比较数组数组的最快方法?
【发布时间】:2018-04-21 19:55:02
【问题描述】:

我有如下数组数组:

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

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

如果您查看前 3 个示例,它们是相同的数组,只是排序不同。

在任何时候我都必须比较两个这样的 AoA 并确定它们是否相同。

最快的方法是什么? 数组本身很小,但我必须经常检查。

【问题讨论】:

标签: python arrays comparison arrayofarrays


【解决方案1】:

您可以使用map(tuple,list)) + 对主列表进行排序(根据整数元素排序对元组进行排序)将子列表转换为元组(不可变)。

l1 = [[0, 3], [0, 4, 1, 5], [0, 2]]
l2 = [[0, 4, 1, 5], [0, 3], [0, 2]]
l3 = [[0, 2], [0, 4, 1, 5], [0, 3]]
print (sorted(map(tuple,l1)) == sorted(map(tuple,l2)))
#True
print(sorted(map(tuple,l2)) == sorted(map(tuple,l3)))
#True
print (sorted(map(tuple,l3)) == sorted(map(tuple,l1)))
#True

l4 = [[0, 4, 1, 5, 3], [0, 2]]
l5 = [[0, 4, 1, 5, 3, 2]]
sorted(map(tuple,l4)) == sorted(map(tuple,l5))
#False

【讨论】:

    【解决方案2】:

    一种方法是将两个数组展平并进行比较。像这样:

    list1 = [[0, 3], [0, 4, 1, 5], [0, 2]]

    list2 = [[0, 4, 1, 5], [0, 3], [0, 2]]

    def 平面(ls): return [val for sublist in ls for val in sublist]

    set(flat(list1)) == set(flat(list2))

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多