简体   繁体   English

使用带有列表理解的条件

[英]using conditional with list comprehension

I'm learning the ropes of python programming and I'm struggling with what might seem simple but confusing to me.我正在学习 python 编程的技巧,我正在努力解决看似简单但令我困惑的事情。 I've got the list my_list and i'd like to subtract 3, only from numbers greater than 9我有列表 my_list,我想减去 3,只能从大于 9 的数字中减去

my_list = [1, 2, 30, 4, 5, 60, 7, 80]

when i try this, i get a Syntax error:当我尝试这个时,我得到一个语法错误:

print([x - 3 if x > 9 for x in my_list])

but adding a useless 'else' conditional at the end of the 'if' conditional makes it work:但是在“if”条件句的末尾添加一个无用的“else”条件句可以使它起作用:

print([x - 3 if x > 9 else x + 0 for x in my_list])

If i did this the longer way:如果我这样做更长的方式:

for j in range(len(my_list)):
    if my_list[j] > 9:
        my_list[j] = my_list[j] - 3
print(my_list)   

I would not need an 'else' conditional to make this work.我不需要“其他”条件来完成这项工作。 Which brings me to the questions;这让我想到了这些问题; is the else clause required for the use of conditionals with list comprehension?使用带有列表理解的条件是否需要 else 子句? If not, how do i make it work without using 'else'?如果没有,我如何在不使用“else”的情况下使其工作?

You need the else in the list comprehension because it needs to know the value to return in the result for every item being iterated over.您需要列表理解中的else ,因为它需要知道要在结果中为每个被迭代的项目返回的值。 There's no automatic default to return the item itself.没有自动默认返回项目本身。 So the conditional expression needs to provide values when the condition is true and also when it's false.因此,条件表达式需要在条件为真时和为假时提供值。

This isn't necessary in the for loop because it's not returning anything, it's executing statements.这在for循环中不是必需的,因为它不返回任何内容,它正在执行语句。 You're modifying the list in place in the if statement, and not doing anything at all when the condition fails.您正在修改if语句中的列表,并且在条件失败时根本不做任何事情。 But there's no such thing as "not doing anything at all" in a conditional expression.但是条件表达式中没有“根本不做任何事情”这样的事情。

If you want to return the value unchanged, use else x -- there's no need to add 0.如果要返回值不变,请使用else x - 无需添加 0。

Simply do the following:只需执行以下操作:

print([x - 3 if x > 9 else x for x in my_list])

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

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