如何在 Python 中使用 for 循环对列表中的字符串进行拆分和排序
尝试读取文件,然后将其存储在列表中,但没有获取所需的输出:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所要做的就是循环遍历句子中的所有单词,然后检查它们是否已在列表中,然后追加它们。
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.