如果列表中的其他理解[重复]

本文解决在Python列表理解中使用if-else结构时的常见语法错误,通过正确示例展示如何根据不同条件对列表元素进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:if else in a list comprehension [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

I have a list l : 我有一个清单l

l = [22, 13, 45, 50, 98, 69, 43, 44, 1]

For numbers above 45 inclusive, I would like to add 1; 对于45以上的数字,我想加1; and for numbers less than it, 5. 对于小于它的数字,5。

I tried 我试过了

[x+1 for x in l if x >= 45 else x+5]

But it gives me a syntax error. 但它给了我一个语法错误。 How can I achieve an ifelse like this in a list comprehension? 我怎样才能在列表理解中实现if - else这样的呢?


#1楼

参考:https://stackoom.com/question/IUIn/如果列表中的其他理解-重复


#2楼

You can also put the conditional expression in brackets inside the list comprehension: 您还可以将条件表达式放在列表解析中的括号中:

    l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
    print [[x+5,x+1][x >= 45] for x in l]

[false,true][condition] is the syntax [false,true] [条件]是语法


#3楼

I just had a similar problem, and found this question and the answers really useful. 我刚遇到类似的问题,发现这个问题和答案真的很有用。 Here's the part I was confused about. 这是我感到困惑的部分。 I'm writing it explicitly because no one actually stated it simply in English: 我是明确写的,因为没有人用英语简单地说出来:

The iteration goes at the end. 迭代结束了。

Normally, a loop goes 通常,循环进行

for this many times:
    if conditional: 
        do this thing
    else:
        do something else  

Everyone states the list comprehension part simply as the first answer did, 每个人都将列表理解部分简单地称为第一个答案,

[ expression for item in list if conditional ] 

but that's actually not what you do in this case. 但这实际上不是你在这种情况下做的事情。 (I was trying to do it that way) (我试图这样做)

In this case, it's more like this: 在这种情况下,它更像是这样的:

[ expression if conditional else other thing for this many times ] 

#4楼

Like in [a if condition1 else b for i in list1 if condition2] , the two if s with condition1 and condition2 doing two different things. 就像在[a if condition1 else b for i in list1 if condition2] ,两个if with condition1condition2做两个不同的事情。 The part (a if condition1 else b) is from a lambda expression: 部分(a if condition1 else b)来自lambda表达式:

lambda x: a if condition1 else b

while the other condition2 is another lambda: 而另一个condition2是另一个lambda:

lambda x: condition2

Whole list comprehension can be regard as combination of map and filter : 整个列表理解可以视为mapfilter组合:

map(lambda x: a if condition1 else b, filter(lambda x: condition2, list1))

#5楼

您必须将表达式放在列表推导的开头,结尾处的if语句过滤元素!

[x+1 if x >= 45 else x+5 for x in l]

#6楼

>>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in l]
[27, 18, 46, 51, 99, 70, 48, 49, 6]

Do-something if <condition> , else do-something else. 如果<condition>那么做,否则做其他事情。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值