我正在尝试按字母顺序对文件中的单词进行排序。但是,程序根据第一个单词对行而不是单词进行排序。在这里。
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
lst2 = line.strip()
words = lst2.split()
lst.append(words)
lst.sort()
print lst
这是我的输入文件
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
这就是我希望得到的
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
最佳答案
lst.append(words)
在 lst
的末尾附加一个列表,它不会连接 lst
和 words
。您需要使用 lst.extend(words)
或 lst += words
。
此外,您不应在每次迭代时对列表进行排序,而应仅在循环结束时进行排序:
lst = []
for line in fh:
lst2 = line.strip()
words = lst2.split()
lst.extend(words)
lst.sort()
print lst
如果你不想重复单词,使用set
:
st = set()
for line in fh:
lst2 = line.strip()
words = lst2.split()
st.update(words)
lst = list(st)
lst.sort()
print lst
关于python - 与 Python 中的拆分函数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33419676/