Here is a simplified example of my problem. I thought that these functions would have exactly the same behavior:
这是我的问题的一个简化例子。我认为这些函数具有完全相同的行为:
def f1(l):
if type(l[0][0])==list: f=lambda x:x[0][0]
else: f=lambda x:x[0]
l.sort(key=f,reverse=True)
def f2(l):
f=lambda x:x[0][0] if type(l[0][0])==list else lambda x:x[0]
l.sort(key=f,reverse=True)
l=[[1,2],[3,4]]
But in reality f1(l)
works fine when f2(l)
collapses with the exception:
但在现实中f1(l)在f2(l)崩溃时可以正常工作:
IndexError: list index out of range
So the question is why is it so and is it possible to use ternary operator that returns one of the functions at all?
问题是为什么会这样,是否有可能使用三元运算符返回一个函数?
1 个解决方案
#1
8
lambda
has the lowest precedence among operators. This is why Python parses that line as
lambda在操作符中具有最低的优先级。这就是为什么Python将这一行解析为as
f = lambda x: (x[0][0] if type(l[0][0]) == list else lambda x: x[0])
The fix is to wrap individual lambda
s in parentheses:
修正方法是将单个的lambdas括在括号中:
f = (lambda x: x[0][0]) if type(l[0][0]) == list else (lambda x: x[0])
That said, type(l[0][0]) == list
is kinda wrong, isinstance(l[0][0], list)
would be the best way (it also handles subclasses of list
).
也就是说,type(l[0][0]) = list有点不对,isinstance(l[0][0], list)是最好的方法(它也处理list的子类)。
#1
8
lambda
has the lowest precedence among operators. This is why Python parses that line as
lambda在操作符中具有最低的优先级。这就是为什么Python将这一行解析为as
f = lambda x: (x[0][0] if type(l[0][0]) == list else lambda x: x[0])
The fix is to wrap individual lambda
s in parentheses:
修正方法是将单个的lambdas括在括号中:
f = (lambda x: x[0][0]) if type(l[0][0]) == list else (lambda x: x[0])
That said, type(l[0][0]) == list
is kinda wrong, isinstance(l[0][0], list)
would be the best way (it also handles subclasses of list
).
也就是说,type(l[0][0]) = list有点不对,isinstance(l[0][0], list)是最好的方法(它也处理list的子类)。