如何在列表理解中做以下操作?与其他通过列表理解
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
嗨WoodChopper。实际上,在for循环中,如果满足条件,则完成一些事情,如果没有满足,则不做任何事情......所以else:pass是多余的。 – Jblasco
@Jblasco:谢谢,我的第一次尝试是'尝试3',只有但没有正确的顺序,因为jaco提到 – WoodChopper