首页 > 解决方案 > 在python中声明一个变量更好:= None,或= str(),或=“”?

问题描述

如果您需要稍后在不同的本地区域内分配它,那么在 python 中将变量声明为 None 会更好吗?我找不到这方面的最佳做法:

  1. 如果它只是一个字符串/整数/布尔值?
  2. 如果它是一个列表/元组/字典?

感谢您的建议!

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

标签: pythonscopeglobal-variablesvariable-declaration

解决方案


大多数时候,如果您不知道要使用哪种结构,您可能无法准确说出您的需求是什么。告诉您需要什么的好方法是您将使用的方法。例如,您使用了 append 方法,它是一种用于列表的方法。因此,您尝试将其定义updated_list为 None 或字符串甚至都行不通,因为它们没有 append 方法。


推荐阅读