2016-03-07 42 views
2
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 su2 

我會有後者可能更多的列表,所以我想自動化我的代碼。如何自動執行我的Python代碼?

list_of_lists= [] 
list_of_lists.append(list1) 
list_of_lists.append(list2) 
list_of_lists.append(list3) 

我已創建list_of lists。但要知道什麼,怎麼通過它循環?

+0

聽起來像[XY問題](http://xyproblem.info)。你想要完成什麼?保持唯一條目的排序數據結構? – L3viathan

+0

@ L3viathan排序數據結構。 –

+0

這可能是矯枉過正,但你可以看看[SortedContainers](http://www.grantjenks.com/docs/sortedcontainers/)庫(及其'SortedSet')。 – L3viathan

回答

3
# Your lists goes here 
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] 

# Collect all the lists 
list_of_lists = [] 
list_of_lists.append(list1) 
list_of_lists.append(list2) 
list_of_lists.append(list3) 

# This list will contain the final result 
result = [] 

# Loop the inner lists from list_of_lists, this will be list1, list2, list3... 
for inner_list in list_of_lists: 
    # Loop each element of the inner lists 
    for element in inner_list: 
     # Make sure the element is not already in the result (this can also be done with sets) 
     if element not in result: 
      # Add the inner element to result 
      result.append(element) 

# Sort the result 
result = sorted(result) 

# Finally output the list 
print result # Outputs: [1.0, 2.0, 2.1, 3.0, 3.1, 4.2, 5.1, 7.2, 9.2] 
+1

那裏有一點解釋,老闆? –

+0

@SterlingArcher現在添加評論。那裏寫作太慢了。 – OptimusCrime

2
import itertools 
su2 = sorted(set(itertools.chain(*list_of_lists)) 

itertools.chain返回發生器遍歷每個表的依次元素,itertools.chain(*list_of_lists)確實是這裏x for lst in list_of_lists for x in lst同樣的事情。

set不是爲每個新值檢查它是否已經在列表中

更有效地進行重複數據刪除它們。最後,sorted各種他們在現有的代碼。