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

发布于 2025-01-17 11:57:05 字数 738 浏览 0 评论 0原文

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

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''''''''''''','kill','the','evious' ,“月亮”],['但是',“软”,“什么”,“光”,“通过”,“ yonder”,“ window'','breaks'],['it'it'is'is'is','' ','','和','juliet','is','the'','sun'],[who'','is'is','','','','',''''''''',''苍白的','with','grief'']]

所需的输出:

['arise','''''it it it'','juliet''','',“已经”,“和”,“ breaks','east'' ','嫉妒','fair','rife'','is'is'is'',kill'','',“月亮”,“苍白”,“病”,“软”,“太阳”,“ “通过”,“什么”,“窗口”,“ with”,“ yonder”]

Trying to read a file then store it in a list but not getting the desired output:

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)

My Output:

[['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']]

Desired Output:

['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']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

埋情葬爱 2025-01-24 11:57:05

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

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)

All you have to do is loop through all of the words in the sentence, then check if they are already in the list, then append them.

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文