python - 在python中声明一个变量更好:= None,或= str(),或=“”?
问题描述
如果您需要稍后在不同的本地区域内分配它,那么在 python 中将变量声明为 None 会更好吗?我找不到这方面的最佳做法:
- 如果它只是一个字符串/整数/布尔值?
- 如果它是一个列表/元组/字典?
感谢您的建议!
def get_executed_list(list_of_strings):
"""list_of_strings is a list"""
updated_list = None
for single_string in list_of_strings:
single_string += "-executed"
updated_list.append(single_string)
return updated_list
或者
def get_executed_list(list_of_strings):
"""list_of_strings is a list"""
updated_list = []
for single_string in list_of_strings:
single_string += "-executed"
updated_list.append(single_string)
return updated_list
或者
def get_executed_list(list_of_strings):
"""list_of_strings is a list"""
updated_list = ""
for single_string in list_of_strings:
single_string += "-executed"
updated_list.append(single_string)
return updated_list
解决方案
大多数时候,如果您不知道要使用哪种结构,您可能无法准确说出您的需求是什么。告诉您需要什么的好方法是您将使用的方法。例如,您使用了 append 方法,它是一种用于列表的方法。因此,您尝试将其定义updated_list
为 None 或字符串甚至都行不通,因为它们没有 append 方法。
推荐阅读
- video - 如何以相同的评级按升序列出电影标题?
- database - 我应该容器化我的数据库吗?如果不是,为什么每个人似乎都这样?
- mysql - 有人可以帮助我解决我的查询类型选择错误
- json - 如何在不编码的情况下将 JSON 文件导入 Excel?
- excel - 是否可以使用输入框从 excel 表中选择一行,然后从该行中选择特定的单元格值来填写其余的 VBA 代码?
- linux - Linux:SFTP尝试失败后不存在目录存在错误?
- mysql - 为什么即使不应该插入 MySQL 仍然插入
- c - 找不到哪个文件代表您需要链接的库
- javascript - Firestore 更新数据未捕获(承诺中) FirebaseError:缺少权限或权限不足
- audio - 使用来自 Audio 对象的预加载音频(即 html 中没有音频标签)