【问题标题】:Does anyone know how to Match two list that are two dimensional list?有谁知道如何匹配两个二维列表?
【发布时间】:2019-09-03 14:28:39
【问题描述】:

我有两个列表,它们是至少有 100 行的二维列表。我想将 A 匹配到 B,反之亦然。但真正的问题不是从 A 逐行输入以匹配 B。有没有更快的方法来循环 B 中的所有行以匹配 B 中的所有行?

我尝试了 a[0] 和 a[1] 和 a[2]。这种方法会起作用,但我必须逐行输入很多内容。这将是很多打字,尤其是如果它有很多行?

我有两个二维列表。我想匹配 A 中的任何值以匹配 B 中的任何值

a=[[9, 15, 25],[4, 14, 18, 25],[11, 12, 24, 25],[4, 8, 9, 26]]

b=[[2, 4, 7, 13, 14],[3, 5, 8, 13, 14],[6, 9, 10, 13, 14],[5, 6, 7, 13, 15],[3, 4, 9, 13, 15],[2, 8, 12, 13, 15],[4, 6, 8, 14, 15],[2, 5, 9, 14, 15]]

b0 = [list(filter(lambda x: x in a[0], sublist)) for sublist in b]

b1 = [list(filter(lambda x: x in a[1], sublist)) for sublist in b]

b2 = [list(filter(lambda x: x in a[2], sublist)) for sublist in b]

b3 = [list(filter(lambda x: x in a[3], sublist)) for sublist in b]

有没有更快的方法来循环遍历所有行?特别是如果有很多行

【问题讨论】:

  • 你的预期输出是什么?
  • 请分享您期望的输出
  • 0.[[], [], [9], [15], [9, 15], [15], [15], [9, 15]] 1. [[4 , 14], [14], [14], [], [4], [], [4, 14], [14]] 2. [[], [], [], [], [], [12], [], []] 3. [[4], [8], [9], [], [4, 9], [8], [4, 8], [9]]。我想找到与 A 中的行号匹配的值。

标签: python list arraylist pattern-matching match


【解决方案1】:

你可以这样做:

for item_a in a:
    result = []
    for item_b in b:
        # Compare elements of lists 
        result.append(list(set(item_a) & set(item_b)))
    print(result)

输出:

[[], [], [9], [15], [9, 15], [15], [15], [9, 15]]
[[4, 14], [14], [14], [], [4], [], [4, 14], [14]]
[[], [], [], [], [], [12], [], []]
[[4], [8], [9], [], [9, 4], [8], [8, 4], [9]]

编辑:

for idx,item_a in enumerate(a):
    result = []
    for item_b in b:
        result.append(list(set(item_a) & set(item_b)))
    print("{} : {}".format(idx,result))

输出:

0 : [[], [], [9], [15], [9, 15], [15], [15], [9, 15]]
1 : [[4, 14], [14], [14], [], [4], [], [4, 14], [14]]
2 : [[], [], [], [], [], [12], [], []]
3 : [[4], [8], [9], [], [9, 4], [8], [8, 4], [9]]

set.intersection() 的解决方案:

for idx,item_a in enumerate(a):
    result = []
    a = set(item_a)
    for item_b in b:
        result.append(list(a.intersection(item_b)))
    print("{} : {}".format(idx,result))

【讨论】:

  • 直到现在才注意到这条评论,但是是的,这样的东西有效。有没有办法显示 A 的行号?
  • 检查我的编辑,如果我理解正确,它应该是解决方案@Sofreshnclean
  • 此解决方案对每个子列表进行多次列表到集合的转换。为了获得更好的性能,可以在单独的循环中将子列表转换为集合。另一种选择是显式调用set.intersection 以避免将操作数转换为集合。
  • 那么你如何设置.intersection?
  • 是的,这是双向的。还有一件事是有办法定义结果的名称吗?
猜你喜欢
  • 2020-01-05
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多