[英]Why does python fail on NoneType when “None” doesnt return in function?
I am trying to create a list of keys from the filteredKeys() function, but when I call the function I get a TypeError: 'NoneType' object is not iterable. 我正在尝试从filteredKeys()函数创建一个键列表,但是当我调用该函数时,我得到了TypeError:'NoneType'对象不可迭代。
'None' doesnt exist when I print the result of filteredKeys() but when I convert it to a list. 当我打印filteredKeys()的结果但将其转换为列表时,不存在“无”。 What am i missing?
我想念什么? It's driving me crazy!
这让我疯狂!
key_list = []
for line in stdout.read().splitlines():
input_line = line
input_line = input_line.replace(b'[sudo] password for ufitadmin: ', b'')
key_individual = str(input_line, 'utf-8')
key_individual = key_individual.replace(
'cat: /home/%s/.ssh/authorized_keys: No such file or directory' % user,
'No key exists for this user.')
key_list.append(key_individual)
global keyDict
keyDict = {}
keyDict[host] = key_list
filterString = "No key exists for this user."
filteredKeylist = []
def filteredKeys():
for key,value in keyDict.items():
for values in value:
if values == filterString:
return key
filteredKeylist = list(filteredKeys())
print(filteredKeylist)
Your filteredKeys()
function is actually very likely to return None
- when none of the values matches filterString
. 你
filteredKeys()
函数实际上很可能回到None
-当没有价值观的匹配filterString
。
Also, you state that you want to "create a list of keys from the filteredKeys() function", but since it returns a single value (either None
or the first key having a value matching filterString
), it just WontWork as you expect. 另外,您声明要“从filteredKeys()函数创建键列表”,但是由于它返回单个值(
None
或第一个键具有匹配filterString
的值),因此它只是WontWork即可。
A better implementation would be to make it a generator: 更好的实现是使其成为生成器:
def filteredKeys():
for key,values in keyDict.items():
if filterString in values:
yield key
filteredKeylist = list(filteredKeys())
but that's still a uselessly complicated way to write: 但这仍然是一种无用的复杂编写方式:
filteredKeylist = [key for key, values in keyDict.items() if filterString in values]
Also globally your code seems overly complicated and I can already spot an obvious bug with keyDict being overwritten on each iteration. 同样在全球范围内,您的代码似乎过于复杂,我已经发现一个显而易见的错误,每次迭代都会覆盖keyDict。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.