2017-03-08 137 views
-1

因此,在構造元組列表時,某些元組內的順序似乎混雜在一起。 each_file[2]內的內容將隨機在內容each_file[1]之前。從印刷文件列表輸出元組隨機切換順序列表

實施例:

[{ef1, ef2}, {ef1, ef2} {ef2, ef1}, {ef1, ef2} ....] 

約約下面的代碼信息:
projectDict是pandas.dataframe對象的列表

filelist = [] 
for each_dict in projectDict: 
    currentDataFrame = projectDict[each_dict] 

    for each_file in currentDataFrame.itertuples(): 
     important_terms = { each_file[1], 
          each_file[2]} 
     filelist.append(important_terms) 

這是使用itertuples的結果,還是在我的代碼中有另一個明顯的錯誤?我用了iterrows並有同樣的問題。我也已經證實,數據不是以輸出的方式構成的。

+2

'important_items'是一組,集合是無序的。 –

+2

這些是**不是**元組,但是**集**和**集的順序未確定**。 –

+0

非常感謝,這是非常愚蠢的錯誤! – Matthew

回答

3

你寫:

important_terms = {each_file[1],each_file[2]} 
#    ^ curly brackets  ^

現在的語法{a,b,...,z}set。在set中,元素最多出現一次次序未確定。像被寫入documentation

set目的是不同可哈希 對象的無序集合。常見用途包括成員資格測試,從序列中刪除重複項 ,並計算數學運算,如交集,聯合,差異和對稱差異等。

語法爲tuple(a,b,...,z)。所以,你應該改變行:

important_terms = (each_file[1],each_file[2]) 
#    ^ round brackets  ^

或者 - 作爲@Matthias說 - 你甚至可以省略圓括弧只有使用逗號:

important_terms = each_file[1],each_file[2] 
#    ^  no brackets  ^

不過,你可以在這裏使用切片由於each_file已經是一個元組:

important_terms = each_file[1:3]

在這裏,你從指數1(含)切片ŧ索引3(不含)。

最後,你可以使用列表理解把你整個程序一個襯墊

filelist = [each_file[1:3] for each_dict in projectDict 
          for each_file in projectDict[each_dict].itertuples()]

甚至更​​優雅:

filelist = [each_file[1:3] for each_dict in projectDict.values() 
          for each_file in each_dict.itertuples()]
+1

你甚至不需要圓括號。 'important_terms = each_file [1],each_file [2]'就夠了,但括號可以作爲視覺幫助添加。 – Matthias

+0

@Matthias:同意。不過,我認爲它可能有用。但我會在答案中加上一個註釋。 –