簡體   English   中英

如何在python中獲取兩個嵌套列表的每個元素的交集?

[英]How to get intersection of each element of two nested lists in python?

我在pyspark環境中工作,如果我有兩個嵌套列表 a和b,

a=[[1,2,3],[8,9,45,0,65],[3,7,23,88],[44,77,99,100,654]]
b=[[1,3,7],[0,9,67,22,45,8,11],[23,3],[100]]

我想要這兩個在python中的交集

intersection_list=[[1,3],[8,9,45,0],[3,23],[100]]

最終的計數是

list_count=[2,3,2,1]

如何在pyspark中獲得此結果?

我努力了

[[[n for n in a if n in b]for x in a]for y in b]

但這並沒有給我所需的intersection_list

在pypark中有沒有辦法用rdd做到這一點?

[[n for n in x if n in y] for x, y in zip(a, b)]

但是,如果子列表很大,那會更好:

[set(x).intersection(y) for x, y in zip(a, b)]

(盡管元素的順序丟失了)

a=[[1,2,3],[8,9,45,0,65],[3,7,23,88],[44,77,99,100,654]]
b=[[1,3,7],[0,9,67,22,45,8,11],[23,3],[100]]

intersection_list = [list(set(x) & set(y)) for x, y in zip(a,b)]

>> [[1, 3], [8, 9, 45, 0], [3, 23], [100]]

list_count = [ len(x) for x in intersection_list ]

>> [2, 4, 2, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM