列表理解中的if语句 [英] The if statement in a list comprehension
本文介绍了列表理解中的if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> row = [1,2,3,4,"--"]
>>> row = [cell.replace("--","hello") for cell in row if cell == "--"]
>>> row
['hello']
如何获得 [ 1,2,3,4,你好]
有列表理解吗?
How can I get [1,2,3,4,"hello"]
with a list comprehension?
推荐答案
[cell.replace( - ,hello)if cell == - else cell for cell in row]
在的
末尾使用
if
时,它会限制考虑哪些项目,因此版本只会返回一个项目,因为源列表中只有一个项目符合条件。
When using the if
at the end of the for
, it restricts which items are considered, so that version will only return one item, since only one item in the source list matches the condition.
此外,在这种情况下,您不需要使用替换
,你可以使用helloif if == -
,但如果你使用这个表格有多个你想操纵的物品。
Also in this case you don't need to use replace
, you could just use "hello" if cell=="--"
instead, but you would use this form if you had multiple items you wanted to manipulate.
这篇关于列表理解中的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文