Python;获取字典的长度作为字典中的一个值
Python; Get the length of a dictionary as a value in the dictionary
我会在我的字典中添加一个包含字典长度的值,例如:
所以我基本上试过了
{..., 'commands' : len(dict) + ' commands are available'}
但它返回给我 NameError: name 'dict' is not defined
我也试过了
def dict_len():
return len(dict)
{..., 'commands' : dict_len() + ' commands are available'}
还有:NameError: name 'dict' is not defined
我该如何解决这个问题?
您没有将参数传递给您定义的函数
def len_dict(dict):
return len(dict)
这就是您使用函数的方式。
我认为您需要完成 python 的基础知识。
首先,不要使用 dict
作为变量名,它已经是 class 所以不要覆盖它。
其次,您想要这样做的方法是先像这样保存您的字典
my_dict = {...} # put whatever values you have in here
然后做
my_dict["commands"] = str(len(my_dict)) + " commands are available"
我会在我的字典中添加一个包含字典长度的值,例如:
所以我基本上试过了
{..., 'commands' : len(dict) + ' commands are available'}
但它返回给我 NameError: name 'dict' is not defined
我也试过了
def dict_len():
return len(dict)
{..., 'commands' : dict_len() + ' commands are available'}
还有:NameError: name 'dict' is not defined
我该如何解决这个问题?
您没有将参数传递给您定义的函数
def len_dict(dict):
return len(dict)
这就是您使用函数的方式。
我认为您需要完成 python 的基础知识。
首先,不要使用 dict
作为变量名,它已经是 class 所以不要覆盖它。
其次,您想要这样做的方法是先像这样保存您的字典
my_dict = {...} # put whatever values you have in here
然后做
my_dict["commands"] = str(len(my_dict)) + " commands are available"