如何在Python中在循环外设置变量
我正在尝试在当前循环的范围之外设置一个变量。
我的情况是这样的:我有两个列表。一个列表包含评论对象,每个评论都有一个用户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的作用域来看,第二个循环中的user = comment_user这一行是在第二个循环的范围内创建了一个新的user变量,这个新变量忽略了第一个循环中定义的user变量。
我使用的是Python 3,所以我想nonlocal关键字可能是解决办法,但我不确定它是否只适用于函数,因为我没能让它工作。
所以,我想知道有没有人能提供一个实现这个目标的方法?有没有更“Pythonic”的方式来做到这一点?
2 个回答
2
我觉得用更符合Python风格的方法是把comment_user
做成一个字典,字典的键是_id
。这样你就不需要一个一个遍历列表,而是可以直接这样做:
for comment in comments:
comment.user_display_name = comment_user[comment['created_by']]['display_name']
2
我觉得问题出在你使用了 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
操作符实际上是检查它们是否是同一个对象。如果这两个字符串是内存共享的,它们可能会给出相同的结果,但一般来说,你不应该用 is
来比较字符串。