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

标签 python for-loop scope

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

我的场景是这样的:我有 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/

相关文章:

python - python中通过函数列表列表

python - 创建列,指示基于其他列的特定值的历史存在性

java - 如何为多个JLabel[]添加鼠标监听器

Javascript:内部数组未重置为外部对象

python - 使用 pandas 合并索引

python - Matplotlib:绘制具有非透明边缘的透明直方图

java,for 循环帮助提供非常基本的 ASCII 控制台输出

java - 将二维数组值更改为零

c - 有没有办法使 C 中的变量只能由声明它的文件访问?

c++ - Boost::log 在初始化后立即停止记录