Python如何對N個列表求交集?

時間 2021-06-08 04:28:26

1樓:EMYG

list1 = ['a','b','f']list2 = ['b','c','d','e']set1 = set(list1) & set(list2) #列出相同元素

set2 = set(list1) ^ set(list2) #列出不同元素

print('相同元素: ',list(set1))print('不同元素: ',list(set2))

2樓:Elvin Peng

a_list=[[

1,2,

3],[2

,3,4

],[3,

4,5]]

result

=set

(a_list[0

])for

data

ina_list[1

:]:result

&=set

(data

)print

result

沒有 @許仙那麼pythonic, 但對於初學者來說可讀性應該更好~

3樓:深海魚

字串本身也是一種列表,以字串為例:

>>>from

functools

import

reduce

>>>L=

['列表1'

,'列表2'

,'列表3'

]>>>

reduce

(lambdax,

y:set(x)

&set(y

),L)

如何在python中,輸入乙個列表(n個1 3的矩陣),使x1 n1 x22 n22

王歡 既然是 的矩陣,完全可以用 numpy 來完成。而且,個人理解,在絕大多數情況下其實並不需要把矩陣中的每個元素都賦值對應到新的單個變數上。也就是說你的需求 可能並不一定很高效。import numpy asnp 從 python list 構建 n x 3 陣列 a np.array list...

python列表如何依次取2個元素?

邢軒 demo lst 1,2,3,4,5 def to sublists lst,length 2 return lst i i length for i in range len lst 1 length print to sublists demo lst letters a b c d e ...

python中如何對列表中元素排序且返回的是每個列表元素的序數?

coder import copyl1 1,4 7,2 9 l2 copy deepcopy l1 深拷貝l1 result list 用來存放結果d dict 借助了python中的dict資料結構l1.sort 對l1進行了排序,會改變l1中值的順序,不過我們已經拷貝了l1 forindex v...