解释python片段

时间:2011-09-02 06:43:32

标签: python

我是python的新手,遇到了这段代码。有人可以帮我解决这里的语法吗?也许就每条线路如何工作提供一些意见? xs是一个包含日期的列表。

    data = {}

    for title, d in tmpdata.items():

        data[title] = [x in d and d[x][statid] or 0 for x in xs]
        data[title][-1] = maxs[statid]

3 个答案:

答案 0 :(得分:4)

如果我不得不猜测,我会说对Python新手来说最令人困惑的一句话就是:

data[title] = [x in d and d[x][statid] or 0 for x in xs]

这里有很多内容,其中一些使用的风格虽然在这种情况下是安全的,但不再推荐使用。这是一个更详细的形式:

data[title] = []
for x in xs:
    if x in d and d[x][statid]:
        data[title].append(d[x][statid])
    else:
        data[title].append(0)

构造condition and value-if-condition-is-true or value-if-condition-is-false是C三元形式condition ? value-if-condition-is-true : value-if-condition-is-false的旧式形式。给定的Python表达式隐藏了一个潜在的错误,如果value-if-condition-is-true被Python评估为“false-y”值,则可能会出现这种错误 - 0, [], ()是所有在以下情况下被视为false的值条件表达式,如果您的value-if-condition-is-true被证明是其中之一,那么您可能会遇到问题。正如在这种情况下发生的那样,如果d[x][statid]为0,那么我们将假设一个假结果并继续向列表中添加0,这无论如何都是正确的。如果我们可以编辑详细表单,最简单的方法是删除and d[x][statid],如下所示:

data[title] = []
for x in xs:
    if x in d:
        data[title].append(d[x][statid])
    else:
        data[title].append(0)

或者使用新的Python三元形式(这给了一些人一些皮疹,但我已经习惯了它 - 三元形式,而不是皮疹),写成:

value-if-condition-is-true if condition else value-if-condition-is-false

或代入我们的详细表格:

data[title] = []
for x in xs:
    data[title].append(d[x][statid] if x in d else 0)

最后,列表理解部分。每当你有这种循环时:

listvar = []
for some-iteration-condition:
    listvar.append(some-iteration-dependent-value)

您可以将其重写为:

listvar = [some-iteration-dependent-value for some-iteration-condition]

这个表单称为列表理解。它通过遵循迭代条件并评估每次迭代的值来创建列表。

因此,您现在可以看到原始语句的编写方式。由于旧式condition and true-value or false-value中可能存在潜在的潜在错误,因此三元形式或明确的if-then-else现在是首选的样式。代码应该今天写成:

data[title] = [d[x][statid] if x in d else 0 for x in xs]

答案 1 :(得分:3)

代码的解释是:

  1. data初始化为空字典

  2. 循环遍历字典tmpdata中的键值对,调用键title和值d

    一个。将新的键值对添加到其键为data的{​​{1}}字典中,其值为以下列表:对于某些(全局?)列表{{1}中的每个title如果x是真实的,则值xs本身,否则为0。

    湾使用x

  3. 覆盖此新值的最后一个单元格

    这里有一些有趣的pythonic结构 - 列表理解和条件表达式的形式和/或形式。

答案 2 :(得分:0)

# Data initialization
data = {}

# for over all the element of the dictionary tmpdata
# title will get the index and d the data of the current element
for title, d in tmpdata.items():

    #data[title]= a list containing each x contained in list xs
    # the x value or 0 depening on the condition "d[x][statid]"
    data[title] = [x in d and d[x][statid] or 0 for x in xs]

    # Assign the value maxs[statid] to the last cell ( I think but not too sure)
    data[title][-1] = maxs[statid]