python - 无法将 for 循环用作列表理解
问题描述
这个 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]
解决方案
考虑这一行GetAsciiListLC()
:
num_list = [(num_list.append((str(num), chr(num)+" "))) for num in range(32, 42, 1)]
num_list.append((str(num), chr(num)+" ")))
改变列表并返回None
.
我想你想要的是这样的:
def GetAsciiListLC():
""" Return list of 2-tuples containing numbers and ASCII equivalents, both as strings. """
return [(str(num), chr(num) + " ") for num in range(32, 42)]
有关从 list.append() 方法返回 None 的基本原理,请参阅此问题: 为什么 append() 在 Python 中总是返回 None?
推荐阅读
- python - `conda update --all` 不改变包的频道
- amazon-web-services - Boto3 DynamoDB ParamValidationError 插入嵌套对象时
- composer-php - 如何在我的机器上设置 COMPOSER_HOME?我有 COMPOSER_AUTH 的凭据
- python - 没有 NumPy 导入的二维数组切片
- javascript - 如何在 HTML 列表中显示这个 JS 数组?
- asp.net-core - Okta 和 asp.net.core 的异常关联失败
- ios - 如何将所有文本字段中的值从 View Controller 传递到 Model 类以将模型逻辑与其解耦?
- javascript - 循环遍历数组并在下拉列表中显示 - Angular
- python - 检查子字符串的字符串列表,不区分大小写
- react-native - React Native Router Flux:抽屉占据整个页面