简体   繁体   English

列表理解Python的多个条件语句

[英]Multiple conditional statements for list comprehension Python

I have a list with elements that I want to do operations on with 2 conditions . 我有一个列表,其中包含要在2个条件下进行操作的元素。

One condition is to multiply a norm function by -1 if the element is negative or leaving the norm function positive if the element is positive. 一种条件是,如果元素为负,则将范数函数乘以-1;如果元素为正,则使范数函数为正。

The list of values looks like this: values列表如下所示:

print(values)

-97476.70633454417
-93170.30642401175
-89901.82679086612
-87187.62533194348
-87269.09594982903
-85513.31676486236
-83545.26529198853
-82411.91255123452
-81620.01849452594

As you can see they are all negative (in this experiment). 如您所见,它们都是负面的(在本实验中)。

The code looks like this: 代码如下:

norm_BIC = [(-1.0) * float(i)/max(values) for i in values if i < 0 or float(i)/max(values) for i in values if i > 0]

If I run the code before the or statement it works: 如果我在or语句之前运行代码,那么它会起作用:

norm_BIC = [(-1.0) * float(i)/max(values) for i in values if i < 0]

Which means it's everything else following that doesn't work because I get an empty list for norm_BIC when running after the or . 这意味着后面的所有其他操作都不起作用,因为在or之后运行时,我得到了norm_BIC的空列表。

How do I fix this condition? 如何解决这种情况?

It seems that you are simply filtering out the negative values and turning them positive. 看来您只是在滤除负值并将其变为正值。 The abs function takes the absolute value, turning your inputs positive. abs函数取绝对值,使输入为正。

would

norm_BIC = [ abs(float(i))/max(values) for i in values]

not fix your problem? 无法解决您的问题?

您应该使用else子句:

norm_BIC = [(-1.0) * float(i)/max(values) if i < 0 else float(i)/max(values) for i in values]

To achieve "this or that" in a list comprehension you need to use an if expression. 要在列表理解中实现“ this or that”,您需要使用一个if表达式。 This allows you to add an else clause as expected — 这使您可以按预期添加else子句-

values = [
    -97476.70633454417,
-93170.30642401175,
-89901.82679086612,
-87187.62533194348,
-87269.09594982903,
-85513.31676486236,
-83545.26529198853,
-82411.91255123452,
-81620.01849452594,

]

norm_BIC = [(-1.0) * float(i)/max(values) if i < 0 else float(i)/max(values) for i in values if i > 0]

The syntax here isn't list-comprehension specific, compare to this if expression — 此处的语法不是列表理解专用的,请与if表达式进行比较-

a = 10 if b < 10 else 20

Running your example values without that final if ie if没有if运行您的示例值而没有最终值

norm_BIC = [(-1.0) * float(i)/max(values) if i < 0 else float(i)/max(values) for i in values]

I get the following output. 我得到以下输出。

[-1.1942744945724522,
 -1.1415129295794078,
 -1.1014678561595233,
 -1.0682137414339221,
 -1.0692119109931586,
 -1.0477002865491576,
 -1.0235879240531134,
 -1.0097022038381638,
 -1.0]

If you just want to ensure the result of your calculation is positive you could use the built-in abs() function. 如果只想确保计算结果为正,则可以使用内置的abs()函数。

norm_BIC = [abs(float(i)/max(values)) for i in values]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM