【发布时间】:2021-10-12 09:49:10
【问题描述】:
我想获得一些帮助,以了解以下代码“从我正在做的一门课程中复制更高或更低的游戏。
对于函数定义为的第二行代码:account_name=account["name"] 我不明白为什么他们将其命名为“帐户”,其中他们指的是键值"name"。当我学习函数时,我认为“帐户”的名称必须说“数据”,因为这是我们将用来获取信息的列表的名称。虽然我们要定义一个新变量,如account_name=data["name"]。但看起来我错了。另一件事是为什么我们将一个值传递给函数“格式化数据”,这在代码中没有作为“帐户”。
所以想知道当列表名称完全不同时,该函数如何获取所有必要的信息,它是如何获取值的。
感谢每一个建议。
from game_data import data
#function that converts the data to a certain format to display
def format_data(account):
account_name=account["name"]
account_follower=account["follower_count"]
account_desc=account["description"]
account_country=account["country"]
return f"{account_name} {account_follower} {account_desc} {account_country}"
#randomly chooses one of the dictionaries from the list
account_a=random.choice(data)
account_b=random.choice(data)
if account_a==account_b:
account_b=random.choice(data)
print(f"compare A: {format_data(account_a)}")
print(f"compare B: {format_data(account_b)}")
【问题讨论】:
-
account_name=data["name"]没有调用函数。该行只是将data["name"]的内容分配给account_name。 -
你指的是什么
list? -
data = [ { 'name': 'Instagram', 'follower_count': 346, 'description': '社交媒体平台', 'country': 'United States' }, { 'name' : 'Cristiano Ronaldo', 'follower_count': 215, 'description': 'Footballer', 'country': 'Portugal' 这就是列表,老实说,当涉及到函数时,我有点困惑,有时你会传递一个值当您在原始代码中定义它时,您只需留空就没有行,例如 account_name=data["name"] 他们有 account_name=account["name"]
标签: python function dictionary