如果i!= 0在列表理解中给出语法错误 [英] if i!=0 in list comprehension gives syntax error

查看:83
本文介绍了如果i!= 0在列表理解中给出语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题非常像: if/else是否在Python的列表理解中? Python中的简单语法错误,否则会导致理解.但是我还是不明白我在这里犯了什么错误:

This question is very much like: if/else in Python's list comprehension? and Simple syntax error in Python if else dict comprehension . But still i dont understand what error I make here:

[i if i!=0 for i in range(2)]
             ^
       syntax error

出于稀疏性,我只希望列表中的条目非零.

I only want the entries in the list that are non-zero for sparsity.

推荐答案

if移至末尾.请参阅有关列表解析的Python文档条目.

>>> [i for i in range(2) if i!=0] # Or [i for i in range(2) if i]
[1]

如果您要查找条件表达式,则可以执行类似@的操作马丁(Martijn)指出,

If you were looking for a conditional expression, you could do something like @Martijn pointed out,

>>> [i if i!=0 else -1 for i in range(2)]
[-1, 1]

如果您只想要非零实体,则还可以 filter(...) 您的列表

If you just want the non zero entities, you could also filter(...) your list.

>>> filter(None, [1, 2, 0, 0, 4, 5, 6])
[1, 2, 4, 5, 6]

这篇关于如果i!= 0在列表理解中给出语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆