如何在 Python 中使用 for 循环拆分和排序列表中的字符串

How do I split and sort strings in a list using for loops in Python

尝试读取文件然后将其存储在列表中但未获得所需的输出:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    #line = line.rstrip()
    words = line.split()
        if words not in lst:
            lst.append(words)
            
lst.sort()
print(lst)

我的输出:

[['Arise', 'fair', 'sun', 'and', 'kill', 'the', 'envious', 'moon'], ['But', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks'], ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'], ['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']

您所要做的就是遍历句子中的所有单词,然后检查它们是否已在列表中,然后追加它们。

fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    #line = line.rstrip()
    words = line.split()
    for word in words:
       if word not in lst:
            lst.append(word)
            
lst.sort()
print(lst)