2015-05-23 205 views
3

所以我的工作,它讀取屏幕上的文本和輸出的代碼以相反的順序的話意味着,如果原文是如何讀取文本文件並以相反的順序輸出文字? Python的

hello world 
how are you 

到:

you are how 
world hello 

我得到它部分工作,問題是它將它輸出到一個列中,但我希望它成爲行。

代碼是

for a in reversed(list(open("text.txt"))): 
    for i in a: 
     a = i.split() 
     b = a[::-1] 
     final_string = '' 
     for i in b: 
      final_string += i + ' ' 
     print(final_string) 
+0

這使得代碼更易於使用有意義的變量名時,理解。 – user2864740

回答

7

您有一個環太多:

for a in reversed(list(open("text.txt"))): 
    for i in a: 

第一環路產生線以相反的順序在該文件中,所以a勢必每一行。第二個for然後通過循環該行中的每個單獨字符。然後繼續「反轉」該字符(或者當該字符是空格或換行符時爲空列表)。

您已使用reversed作爲該文件,您也可以將它用於該行;與str.join()結合起來:

for line in reversed(list(open("text.txt"))): 
    words = line.split() 
    reversed_words = ' '.join(reversed(words)) 
    print(reversed_words) 

或者更簡潔依然:

print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n') 

演示:

>>> with open('text.txt', 'w') as fo: 
...  fo.write('''\ 
... hello world 
... how are you 
... ''') 
... 
24 
>>> for line in reversed(list(open("text.txt"))): 
...  words = line.split() 
...  reversed_words = ' '.join(reversed(words)) 
...  print(reversed_words) 
... 
you are how 
world hello 
>>> print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n') 
you are how 
world hello 
+0

啊謝謝,第一個是正確的,現在我只有一個問題,如果你可以向noob解釋它,那麼exactli reverse_words =''.join(顛倒過來)是什麼意思?我真的會認爲 –

+0

@AleksČerneka:'倒過來(單詞)'給你倒過來的話。 '''.join()'將單詞連接起來,並將每個單詞之間的''''放在一起。 –

+0

哎呀。我現在看到了。對於那個很抱歉。 – Kyrubas

相關問題