如何在字典中使用for循环

Har*_*mer 3 python dictionary

谁能解释一下下面的实现:

item = dict((i.tag, (type(i.text) == str and i.text.strip() or i.text)) for i in r if i.tag != "tid_item")
Run Code Online (Sandbox Code Playgroud)

我在各种变量中得到的值:

r is something like : <Element 'Rows' at 0x0000000003DA4540>
i.tag : resultNum
i : <Element 'resultNum' at 0x0000000003EA45A0>
i.text : 1
Run Code Online (Sandbox Code Playgroud)

我是 python 新手,我无法理解如何在字典中使用 forloop,因为值也是荒谬的。

感谢帮助!

小智 5

让我们首先使代码更清晰:

dict(               #  constructor
    (i.tag,         #  key
         (type(i.text) == str and i.text.strip() or i.text)     # value
    ) 
    for i in r                  # driver of the generator
    if i.tag != "tid_item"      # conditional selector
)
Run Code Online (Sandbox Code Playgroud)

这里还不是字典,而是使用生成器的字典构造函数。运行后,item分配给它的变量将包含一个字典

这个构造函数中的 for 循环是创建所有元素的生成器:它循环 r 中的所有元素,如果满足条件,那么它将创建一个元组 ( key, value) -> 创建一个 'on-the-fly ' 元素列表。

如果我们以不同的方式编写它,“值”的布尔选择器也很简单:

value = i.text.strip() if (type(i.text) == str) else i.text
Run Code Online (Sandbox Code Playgroud)