python - 如何解决“'NoneType'类型的参数不可迭代”的问题?
问题描述
我试图解决一个 Python 练习,但我的程序在运行时崩溃了。
练习指导如下:
打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印。
这是我的代码:
fname = input("Enter file name: ")
fh = open(fname)
j=-1
glolist=list()
for line in fh:
line=line.rstrip()
lst=line.split()
nb=len(lst)
i=0
while i< nb:
if lst[i] not in glolist: #argument of type 'NoneType' is not iterable"
i=i+1
else:
j=i
i=i+1
if j==-1:
glolist=glolist+lst
else:
h=0
while h<j:
glolist=lst.append(lst[h])
h=h+1
h=h+1
while h<nb:
glolist=lst.append(lst[h])
h=h+1
glolist=glolist.sort()
print(glolist)
解决方案
fname = input("Enter file name: ")
fh = open(fname)
words=list()
for line in fh:
line=line.rstrip()
lst=line.split()
i=0
while i<len(lst):
str=lst[i]
if str in words:
i=i+1
else:
words.append(str)
i=i+1
words.sort()
print(words)
推荐阅读
- android - 如何基于谷歌最新的 Android 拨号器应用程序(或基于原版的 ROM,如 Lineage OS)制作拨号器?
- c# - 有没有办法不必使用常量表达式作为属性参数?
- amazon-ec2 - 如何解决 AWS EC2 中的“ssh:连接到主机 ec2-XX-XX-XX-XX.compute-1.amazonaws.com 端口 22:连接超时”错误
- java - 方法引发了“java.lang.StackOverflowError”异常。无法评估 com.sun.proxy.$Proxy0.toString()
- c# - 使用 Json.NET 将 JObject 转换为 Dictionary
- opencv - cv_bridge 动态模块没有定义模块(PyInit_cv_bridge_boost)
- ios - UIWebView webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:] + 92
- java - 对 servlet 的 POST 请求返回 GET 方法的结果
- azure-devops - Azure DevOps:如果出现任何故障,要运行的任务的自定义条件
- php - 如何“检查 POST Array 上是否有重复值”?