问题
I am confused with the following line of code:
data = {n.attributes['xid']: float(n.content) if n.content else np.nan for n in graph.by_tag('value') }
The dictionary comprehension consists of if-else
and for
loop. Can anyone explain me how the code works?
回答1:
Does a translation help?
data = {}
for n in graph.by_tag('value'):
if n.content:
data[n.attributes['xid']] = float(n.content)
else:
data[n.attributes['xid']] = np.nan
回答2:
You are confused by the ... if ... else ... conditional expression. It is not part of the loop, it is part of the expression generating the value for each key-value pair.
A dictionary comprehension consists of at least one loop, with optionally more loops and if
filters on the right-hand side, and two expressions on the left. One expression to produce a key, and another to produce a value. Together the two expressions make a key-value pair for the resulting dictionary:
{key_expression: value_expression for target in iterable}
The conditional expression simply produces a value based on a test. Either the test evaluates to true and one value is picked, or the value is false and the other is picked:
true_expression if test else false_expression
Only the expression picked is evaluated; if test
ends up as false, the false_expression
is executed and the result is returned, the true_expression
is ignored entirely.
Thus, the dictionary comprehension you are looking at is the equivalent of:
data = {}
for n in graph.by_tag('value'):
key = n.attributes['xid']
value = float(n.content) if n.content else np.nan
data[key] = value
So the value
is either set to float(n.content)
, or to np.nan
, depending on the value of n.content
(truethy or not).
来源:https://stackoverflow.com/questions/25989055/in-python-how-does-if-else-and-for-in-a-dictionary-comprehension-work