Python 跳过单行for循环语句中的元素

Python 跳过单行for循环语句中的元素,python,python-3.x,list-comprehension,Python,Python 3.x,List Comprehension,在使用for循环时,是否有方法跳过for循环的迭代 [x if cond else pass for x in seq] 我在尝试时遇到语法错误 Output >>> File "<ipython-input-122-a943adcf1b68>", line 1 test = [pass if isinstance(x, float) else x for x in test_list] ^

在使用for循环时,是否有方法跳过for循环的迭代

[x if cond else pass for x in seq]
我在尝试时遇到语法错误

Output >>> File "<ipython-input-122-a943adcf1b68>", line 1
            test = [pass if isinstance(x, float) else x for x in test_list]
                       ^
      SyntaxError: invalid syntax
输出>>>文件“”,第1行
测试=[如果在测试列表中存在(x,浮点)或x代表x,则通过]
^
SyntaxError:无效语法
您将循环过滤器与循环过滤器混淆。要筛选列表中的元素,请将
if
放在它筛选的
for
循环之后:

[x for x in seq if cond]
条件表达式(
expr1 if cond else expr2
)必须始终生成一个值,因为它是一个表达式
pass
不是一个表达式,它是一个语句,只能自己使用

对于您的具体示例,如果要选择值不浮动的元素,则要在过滤器测试中使用
not

[x for x in test_list if not isinstance(x, float)]

这就解决了语法错误。但即使这样,也不会跳过x出现在输出中list@Inc0gnito:您没有提供任何样本数据,因此我无法告诉您哪里出了问题。也许
test\u list
中的所有值都是字符串,因此
isinstance(x,float)
永远不会为真。然而,这将是一个不同的问题。