簡體   English   中英

在Python中查找列表的並集

[英]Finding a union of lists of lists in Python

假設我們有

 temp1 = [1, 2, 3]
 temp2 = [1, 2, 3]
 temp3 = [3, 4, 5]

如何獲得三個臨時變量的並集?

預期結果: [[1,2,3],[3,4,5]]

您可以使用內置set來獲取唯一值,但是要使用list對象達到此目的,您首先需要將其轉換為可哈希(不可變)對象。 一個選項是tuple

>>> temp1 = [1,2,3]
>>> temp2 = [1,2,3]
>>> temp3 = [3,4,5]
>>> my_lists = [temp1, temp2, temp3]

>>> unique_values = set(map(tuple, my_lists))
>>> unique_values  # a set of tuples
{(1, 2, 3), (4, 5, 6)}

>>> unique_lists = list(map(list, unique_values))
>>> unique_lists  # a list of lists again
[[4, 5, 6], [1, 2, 3]]

我創建了一個matrix來為通用輸入輕松更改代碼:

temp1=[1,2,3]
temp2=[3,2,6]
temp3=[1,2,3]
matrix = [temp1, temp2, temp3]

result = []
for l in matrix:
    if l not in result:
        result.append(l)

print result

暫無
暫無

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

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