gpt4 book ai didi

python - 如何在python中的循环外设置变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:37:12 27 4
gpt4 key购买 nike

我试图在当前循环范围之外设置一个变量。

我的场景是这样的:我有 2 个列表。一个包含评论对象列表,每个评论都有一个对用户 ID 的引用。我的第二个列表包含基于用户 ID 的所有用户对象。

我想做的是遍历每条评论,然后修改列表中的评论对象以包含用户名,这样当我传回评论列表时,它就会嵌入名称。

到目前为止,这是我试图实现这一目标的方式:

# iterate through the comments and add the display name to the comment obj
for comment in comments:
# Create the user to use later
user = None

# Iterate the comment_users and get the user who matches the current comment.
for comment_user in comment_users:

if comment_user['_id'] is comment['created_by']:
user = comment_user # this is creating a new user in the for comment_user loop
break

print(user)

# get the display name for the user
display_name = user['display_name']

# Add the user display name to the comment
comment.user_display_name = display_name

现在,从我开始从 Python 的范围理解,第二个 for 循环中的 user = comment_user 行正在第二个 for 循环的范围内创建一个新的用户变量,它忽略了定义的用户变量在第一个 for 循环中。

我使用的是 Python 3,所以我认为 nonlocal 关键字是可行的方法,但我不确定这是否仅适用于函数,因为我无法让它工作。

所以,我想知道是否有人可以提供实现这一目标的方法?是否有更“pythonic”的方式来实现这一目标?

最佳答案

我认为问题是您对 is 的使用。试试这个代码:

for comment in comments:
for comment_user in comment_users:
if comment_user['_id'] == comment['created_by']:
comment.user_display_name = comment_user['display_name']
break

当您(错误地)使用 is 来比较 string 对象时,会出现此问题。相等运算符 (==) 检查两个字符串的内容是否相同,而 is 运算符实际上检查它们是否相同目的。如果字符串是 interned ,它们可能会给出相同的结果,但一般来说,您永远不应该使用 is 进行字符串比较。

关于python - 如何在python中的循环外设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22731631/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com