为什么这个Python列表推导失败了?

huangapple go评论62阅读模式
英文:

Why is this Python list comprehension failing?

问题

以下是要翻译的内容:

为什么以下代码失败?我收到一个'd_item'未定义的错误。

inp = [{'Math': 90, 'Science': 92}, {'Math': 89, 'Science': 94}, {'Math': 92, 'Science': 88}]
d = [value for key, value in d_item.items() for d_item in inp]

然而,这段代码可以运行:

inp = [{'x': '10', 'y': '20', 'z': '30'}, {'p': '40', 'q': '50', 'r': '60'}]
ints = [dict([key, int(value)] for key, value in item.items()) for item in inp]

据我所知,它们都遵循相同的约定。

我已经卡在这个问题上太长时间了,为什么第二个代码块允许我在for语句之前使用变量名,而第一个代码块不允许?

英文:

Why does the following code fail? I'm getting a 'd_item' is not defined error.

inp = [{'Math': 90, 'Science': 92}, {'Math': 89, 'Science': 94}, {'Math': 92, 'Science': 88}]
d = [value for key, value in d_item.items() for d_item in inp]

Yet this code runs:

inp = [{'x': '10', 'y': '20', 'z': '30'}, {'p': '40', 'q': '50', 'r': '60'}] 
ints = [dict([key,int(value)] for key, value in item.items()) for item in inp]

They both follow the same convention as far as I can tell.

I've been stuck on this for too long, why does the second code block let me use a variable name before its stated in a
for statement but the first one does not?

答案1

得分: 1

这是一个不错的解释关于如何处理嵌套的东西。

所以你的语法应该是:

d = [value for d_item in inp for key, value in d_item.items()]

至于为什么第二个例子有效,字典的创建是一个表达式(带有内部循环),基于其旁边的隐式(单一)循环。

ints = [dict([key,int(value)] for key, value in item.items()) for item in inp]

^ 单一表达式(带有内部循环) ^ for循环

英文:

Start by reading this: https://stackoverflow.com/questions/25674169/how-does-the-list-comprehension-to-flatten-a-python-list-work

It is a pretty good explanation of how nested things are handled.

So your syntax should be:

d = [value for d_item in inp for key, value in d_item.items() ]

as for why the second works, the dict creation is 1 expression (with an internal loop), based on the implicit (single) loop next to it.

ints = [dict([key,int(value)] for key, value in item.items()) for item in inp]
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^      ^^^^^^^^^^^
                single expression (with internal loop)              for-loop

huangapple
  • 本文由 发表于 2023年6月19日 03:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定