我的代碼比較兩個列表和提取元素
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]
是否爲了此事? –
@GarrettR是的,後者我會有更多的列表。 –
如果你想要的元素,排序你應該使用我的解決方案,因爲它保證元素是遞增順序返回 –