解释python段
我是python新手,遇到了这段代码。有人能帮我解释一下这里的语法吗?也许在每一行上提供一些关于它如何工作的评论解释python段,python,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] 有关守则的解释如下: 初始化数据到空字典 循环
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]
有关守则的解释如下:
数据
到空字典tmpdata
中的键值对,调用键标题
和值d
a。向数据
字典添加一个新的键值对,其键值为标题
,其值为以下列表:对于某些(全局)列表中的每个x
,如果d[x][statid]
为0,则值x
本身为0
b。用maxs[statid]
这里有一些有趣的Python结构-列表理解和条件表达式的和/或形式。如果让我猜的话,我想对Python新手来说,最令人困惑的一句话一定是:
# 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]
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)
data[title] = []
for x in xs:
data[title].append(d[x][statid] if x in d else 0)
如果条件为真,则构造条件和值;如果条件为假,则构造条件和值
是C三元形式条件的旧式形式?条件为真时的值:条件为假时的值
。给定的Python表达式隐藏了一个潜在的bug,如果Python将值if condition is true
计算为“false-y”值-0、[]、()
都是在条件表达式中使用时会被视为false的值,因此,如果您的值if condition为true
被证明是其中之一,您可能会遇到问题。在本例中,如果d[x][statid]
为0,那么我们将假设一个错误的结果,并继续向列表中添加一个0,这将是正确的操作。如果我们只需编辑详细表单,最简单的方法就是删除和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:
if x in d and d[x][statid]:
data[title].append(d[x][statid])
else:
data[title].append(0)
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]
这种形式叫做列表理解。它通过遵循迭代条件并计算每个迭代的值来创建一个列表
现在你可以看到原始语句是如何编写的。由于旧式条件和真值或假值
可能存在固有的潜在缺陷,现在首选三元形式或显式if-then-else。今天,代码应该写成:
data[title] = [d[x][statid] if x in d else 0 for x in xs]
不,如果d中的x和d[x][statid]
,那么data[title]
将附加d[x][statid]
中的值,而不是x。我认为任何体面的在线教程都会涵盖这些内容。“this”的具体含义是什么?当然,很多Python的经验都只是在尝试。打开一个解释器,开始实验——你(可能)不会破坏任何东西。