在Python列表推导中对if/elif语句使用'for'循环 [英] Use a 'for' loop with if/elif statement in Python list comprehension
本文介绍了在Python列表推导中对if/elif语句使用'for'循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将此for循环转换为列表理解:
I am trying to translate this for loop into a list comprehension:
a = [1,2,3,4,5,6,7,8,9]
result = []
for i in a:
if i <= 3:
result.append(1)
elif i > 4 and i < 7:
result.append(2)
我已经尝试过了
[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
抱怨
File "<ipython-input-155-eebf07a9e0d8>", line 2
[1 if i <= 3 else 2 if i > 3 and i < 7 for i in a]
^
SyntaxError: invalid syntax
推荐答案
列表理解:
添加更多条件:D(不,这真的很混乱)
List comprehension:
Add some more conditions :D (no this is really messy)
[
1 if i <= 3 else 2
for i in a
if i != 4 and i < 7
]
我们怎么到这里的?
基本列表组合:
[EXPRESSION for TARGET in ITERABLE if CONDITION]
三元表达式:(IF_TRUE if CONDITION else IF_FALSE)
- 进入for循环.足够简单的
for i in a
. - 添加条件以过滤掉将被忽略的项目.一旦通过
CONDITION
,列表中的那个位置就必须有一个项目.在这种情况下,我们不希望i
是4或大于7.if i != 4 and i < 7
. - 用物品做您需要的事情.在这种情况下,如果
i
小于或等于4,我们需要1
.否则,我们将取2.1 if i <= 3 else 2
.注意:这是一个三元表达式.检查出来!
- Get the for loop in. Simple enough
for i in a
. - Add conditions that filter out items which will be ignored. Once it gets past
CONDITION
, there has to be an item in the list at that position. In this case, we don't wanti
if it's 4 or greater than 7.if i != 4 and i < 7
. - Do what you need with the item. In this case, we want
1
ifi
is smaller or equal to 4. Otherwise, we'll take 2.1 if i <= 3 else 2
. Note: this is a ternary expression. Check them out!
这篇关于在Python列表推导中对if/elif语句使用'for'循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文