您有一個環太多:
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
這使得代碼更易於使用有意義的變量名時,理解。 – user2864740