2016-09-30 70 views
1

我想打開一個文件,拆分它,按字母順序排序,然後刪除重複項。我已經能夠打開文件,分割文件,正確排列文件,並將其放入列表中,但是我很難對其進行重複數據刪除。我將如何去打印出一個按字母順序排列和重複數據刪除的列表?從文件中刪除重複列表,同時保持順序-python3.5

這是我目前有:

userinp = input('Enter file: ') 
romeo = open(userinp) 
inp = romeo.read() 
sections = inp.split() 
sections.sort() 
shakespeare = list(sections) 
for i in sections: 
    if i not in shakespeare: 
     shakespeare.append(i) 
print(shakespeare) 
+0

即時通訊有點問題了解你想做什麼。 – Fallenreaper

+0

對不起。我正在嘗試從文件中刪除重複文字,並按字母順序打印出來。我遇到的麻煩是將其重複數據刪除並按字母順序排列。我能夠得到一個或另一個,但不能兩個。那有意義嗎? – jaywah

+0

我的意思是,你可以做到這一點。所以以我的答案爲例,它顯示了排序數組上的列表重複。你想在排序之前複製嗎? – Fallenreaper

回答

0

我只是做一個簡單的示例:

a = [9,8,7,6,5,4,3,2,1] 
for i in a: 
    b[i] = 0 
b = [x for x in b] 

這將限制你的結果集。

在代碼中,使用相同的過程:

userinp = input('Enter file: ') 
romeo = open(userinp) 
inp = romeo.read() 
sections = inp.split() 
shakespeare = {} 
for i in sections: 
    shakespeare[i] = 0 
shakespeare = [x for x in b] 
print(shakespeare) 

我的前提是:

  • 遍歷數組,並注入到地圖中創造一個獨特的密鑰。
  • 然後在地圖上循環,將其變回列表。
    • 這是通過在排序的莊園中散步數組自動排序的,但是您可以隨時調用.sort()來重新確認您是否選擇。
0

使用OrderedDict

說你有file.txt包含

b 
b 
c 
a 

你可以做

from collections import OrderedDict 

with open('file.txt', 'rb') as f: 
    lines = f.readlines() 
    lines.sort() 
    for line in OrderedDict.fromkeys(lines): 
     print(line.strip()) 

這將打印出

a 
b 
c 
相關問題