gpt4 book ai didi

python - 检查列表数组是否包含另一个列表中的元素

转载 作者:太空狗 更新时间:2023-10-30 01:01:29 27 4
gpt4 key购买 nike

给定一个列表数组 a,以及另一个列表 bd。我如何检查 a 中的列表元素是否存在于 b 中(或者另一个例子,在 d 中)?我知道我可以使用 a for 元素循环并检查每个元素是否在 b/d 中,但是是否有任何 API做的快吗?

 a = [[1,4], [17,33,2],[2,33]]

b = [1,4,5,6]
c = [[1,4]]

d = [2,33]
e = [[17,33,2],[2,33]]

这么说吧,给定列表ab,我怎样才能高效地写出下面的循环呢?假设使用列表理解在一行中说。

        newls = []
for sublist in a:
newls.append(list(set(sublist).intersection(set(b))))

最佳答案

我怀疑这是您真正想要的,但这是您所要求的,即产生与 for 循环相同结果的单行列表理解:

newls = [list(set(sublist).intersection(set(b))) for sublist in a]

a = [[1,4], [17,33,2],[2,33]]
b = [1,4,5,6]
>>> c = [list(set(sublist).intersection(set(b))) for sublist in a]
>>> c
[[1, 4], [], []]

您可能不希望其中有空列表,所以:

>>> c = filter(None, [list(set(sublist).intersection(set(b))) for sublist in a])
>>> c
[[1, 4]]

请注意,这并没有给出第二种情况的预期结果:

a = [[1,4], [17,33,2],[2,33]]
d = [2,33]
e = filter(None, [list(set(sublist).intersection(set(d))) for sublist in a])

>>> e
[[33, 2], [33, 2]]

关于python - 检查列表数组是否包含另一个列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25417911/

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