2016-03-03 51 views
2

我的代碼比較兩個列表和提取元素

with open('freq1.txt') as f: 
    next(f, None) 
    list1 = [line.rstrip() for line in f] 

with open('freq2.txt') as f: 
    next(f, None) 
    list2 = [line.rstrip() for line in f] 

print set(list1).intersection(list2) 

但我得到 集([]) 比如我有兩個列表

list1=[1,2,3,4] 
list2=[3,2,7,5,9] 

我想從list1的所有元素和列表list2

newlist=[1,2,3,4,5,7,9] 

如何寫?

編輯 我想使用一種使用列表解析的方式。

list1=[1.0,2.0,3.1,4.2] 
list2=[3.0,2.0,7.2,5.1,9.2] 
list3=[2.1,4.2,5.1,9.2] 

su1 = list1 + [x for x in list2 if x not in list1] 
su2= su1 + [x for x in list3 if x not in su1] 
su2=sorted(su2) 
print su2list1=[1.0,2.0,3.1,4.2] 
list2=[3.0,2.0,7.2,5.1,9.2] 
list3=[2.1,4.2,5.1,9.2] 

su1 = list1 + [x for x in list2 if x not in list1] 
su2= su1 + [x for x in list3 if x not in su1] 
su2=sorted(su2) 
print su2 

作品非常漂亮

[1.0, 2.0, 2.1, 3.0, 3.1, 4.2, 5.1, 7.2, 9.2] 
+0

是否爲了此事? –

+0

@GarrettR是的,後者我會有更多的列表。 –

+0

如果你想要的元素,排序你應該使用我的解決方案,因爲它保證元素是遞增順序返回 –

回答

5

你想set.union()

>>> set(list1).union(list2) 
set([1, 2, 3, 4, 5, 7, 9]) 

如果你想有一個列表作爲結果(如果你不想使用它是沒有必要的列表的屬性,如索引和,如果你只處理整數,因爲,因爲整數散列等於自己(除-1是-2)set()對象也會保存順序),您可以調用list()函數對union()的結果。

>>> list(set(list1).union(list2)) 
+0

我不完全確定,但我相信套是無序的容器。訂單取決於散列 - 用戶無法控制訂單,因此如果輸入與實際或整數不同,則訂購輸出將與預期不同。我只是提到這一點,因爲你在上面做了一個非常強大的聲明,並不適用於許多情況。 – PyNEwbie

+0

@PyNEwbie是的我剛纔提到這是用於整數。 – Kasramvd

+0

@Kasramvd在我的情況下,我有實數不是整數。 –

1

如果你想要的元素按升序排序

sorted_unique = sorted(set(list1+list2)) 
+0

看到我上面的評論,這並不適用於所有情況,在轉換爲集合之前對列表進行排序看起來很嘈雜,如果輸入集合中的輸入(排序([1,2,3,4] + [ ([1,2,4,3] + [5,6,7,8,9])) – PyNEwbie

+0

修復它..感謝 –