这个for循环可以正常工作,但不能作为列表理解。 理解为每个迭代创建空元素。 有人能解释什么是错误的以及如何修复它吗
def GetAsciiList():
num_list = []
for num in range(32, 42, 1):
num_list.append((str(num), chr(num)+" "))
return num_list
def GetAsciiListLC():
num_list = []
num_list = [(num_list.append((str(num), chr(num)+" "))) for num in range(32, 42, 1)]
return num_list
print GetAsciiList()
print GetAsciiListLC()
控制台输出:
[('32', ' '), ('33', '! '), ('34', '" '), ('35', '# '), ('36', '$ '), ('37', '% '), ('38', '& '), ('39', "' "), ('40', '( '), ('41', ') ')]
[None, None, None, None, None, None, None, None, None, None]
在{{CD1}}中考虑此行:
num_list.append((str(num), chr(num)+" ")))
对列表进行变异并返回None
我想你想要的是:
有关从list.append()方法返回None的基本原理,请参见此问题: Why does append() always return None in Python?
相关问题 更多 >
编程相关推荐