Find intersection of two nested lists?

前端 未结 20 1540
星月不相逢
星月不相逢 2020-11-22 04:16

I know how to get an intersection of two flat lists:

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]

or

<
20条回答
  •  感动是毒
    2020-11-22 04:54

    # Problem:  Given c1 and c2:
    c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
    c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
    # how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?
    

    Here's one way to set c3 that doesn't involve sets:

    c3 = []
    for sublist in c2:
        c3.append([val for val in c1 if val in sublist])
    

    But if you prefer to use just one line, you can do this:

    c3 = [[val for val in c1 if val in sublist]  for sublist in c2]
    

    It's a list comprehension inside a list comprehension, which is a little unusual, but I think you shouldn't have too much trouble following it.

提交回复
热议问题