在Python中的嵌套列表中查找匹配项

时间:2010-06-13 01:53:05

标签: python list nested

我有两个不同大小的嵌套列表:

A = [[1, 7, 3, 5], [5, 5, 14, 10]]

B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]

我想收集列表B中的所有嵌套列表,如果A [2:4] == B [2:4]并将其放入列表L:

L = [[1, 17, 3, 5], [141, 25, 14, 10]]

此外,如果匹配发生,那么我想将子列表B的最后一个元素更改为子列表A的第一个元素,因此最终解决方案将如下所示:

L1 = [[1, 17, 3, 1], [141, 25, 14, 5]]

2 个答案:

答案 0 :(得分:3)

看起来这样做你想要的:

> [b for b in B if b[2:4] in [a[2:4] for a in A]]
[[1, 17, 3, 5], [141, 25, 14, 10]]

但是,为了提高效率,您可能需要预先计算A的切片。

> a_slices = [a[2:4] for a in A]
> [b for b in B if b[2:4] in a_slices]
[[1, 17, 3, 5], [141, 25, 14, 10]]

这似乎符合您的新要求:

> [b[:-1] + a[:1] for b in B for a in A if b[2:4] == a[2:4]]
[[1, 17, 3, 1], [141, 25, 14, 5]]

答案 1 :(得分:1)

[x for x in B if any(x[2:4] == y[2:4] for y in A)]