我怀疑这是你真正想要的,但它是你所要求的,即一行列表理解产生与你的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]]