如果Python没有三元条件运算符,是否可以使用其他语言结构模拟一个?
我想弄清楚Python lambdas.lambda是现实生活中应该被遗忘的"有趣"语言项目之一吗?
我确信有一些可能需要它的边缘情况,但考虑到它的模糊性,它在未来版本中重新定义的可能性(我基于它的各种定义的假设)和降低的编码清晰度 - 应该是要避免吗?
这让我想起C类型的溢出(缓冲区溢出) - 指向顶部变量并重载以设置其他字段值.感觉就像是一种技术表演,但维护编码器的噩梦.
来自python wiki:
In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods).
我不明白为什么在py3.0中删除cmp的原因
考虑这个例子:
>>> def numeric_compare(x, y):
return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
现在考虑这个版本(推荐并与3.0兼容):
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return …Run Code Online (Sandbox Code Playgroud)