Python 如何对文本文件中的单词进行排序?
在“test_wordss.txt”中 我的代码:Python 如何对文本文件中的单词进行排序?,python,Python,在“test_wordss.txt”中 我的代码: for line2 in open('C://Users/Desktop/test_wordss.txt'): fields2 = line2.rstrip('\n').split('\t') print fields2.sort() 我代码的结果显示为无 我做错什么了吗? 对文本文件中的单词排序有任何建议吗?sort不会返回sorted列表,而是sort将列表排序到位。尝试: words = sorted(open('C:/
for line2 in open('C://Users/Desktop/test_wordss.txt'):
fields2 = line2.rstrip('\n').split('\t')
print fields2.sort()
我代码的结果显示为无
我做错什么了吗?
对文本文件中的单词排序有任何建议吗?
sort
不会返回sorted
列表,而是sort
将列表排序到位。尝试:
words = sorted(open('C://Users/Desktop/test_wordss.txt').read().split())
print(words)
您的代码有几个问题:
sort()
不返回已排序的列表。它对列表进行适当排序,并返回None
for line in sorted(file('C://Users/Desktop/test_wordss.txt').read().split("\n")):
print line
sort
对列表进行适当排序,并返回None
以说明这一点(这样你就不会忘记副作用,你只会得到副作用)。任用
print sorted(fields2)
或
回答得好!它的与众不同之处在于它能够解释和帮助用户,而不需要提供太多的原始代码!回答得好,解释他的代码有什么问题。
print sorted(fields2)
fields2.sort()
print fields2