使用Else传递进行列表理解
问题描述
如何在列表理解中执行以下操作?
test = [["abc", 1],["bca",2]]
result = []
for x in test:
if x[0] =='abc':
result.append(x)
else:
pass
result
Out[125]: [['abc', 1]]
尝试1:
[x if (x[0] == 'abc') else pass for x in test]
File "<ipython-input-127-d0bbe1907880>", line 1
[x if (x[0] == 'abc') else pass for x in test]
^
SyntaxError: invalid syntax
尝试2:
[x if (x[0] == 'abc') else None for x in test]
Out[126]: [['abc', 1], None]
尝试3:
[x if (x[0] == 'abc') for x in test]
File "<ipython-input-122-a114a293661f>", line 1
[x if (x[0] == 'abc') for x in test]
^
SyntaxError: invalid syntax
解决方案
if
需要在末尾,列表理解中不需要pass
。仅当满足if
条件时才会添加该项,否则将忽略该元素,因此pass
是在列表理解语法中隐式实现的。
[x for x in test if x[0] == 'abc']
为了完整起见,此语句的输出为:
[['abc', 1]]
相关文章