如何在列表理解中做以下操作?與其他通過列表理解
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