Python 2.x有两种方法可以重载比较运算符,__cmp__或者"丰富的比较运算符",如__lt__. 丰富的比较超载被认为是首选,但为什么会这样呢?
丰富的比较运算符更容易实现每个,但您必须使用几乎相同的逻辑实现其中几个.但是,如果你可以使用内置cmp和元组排序,那么__cmp__变得非常简单并完成所有的比较:
class A(object):
def __init__(self, name, age, other):
self.name = name
self.age = age
self.other = other
def __cmp__(self, other):
assert isinstance(other, A) # assumption for this example
return cmp((self.name, self.age, self.other),
(other.name, other.age, other.other))
Run Code Online (Sandbox Code Playgroud)
这种简单性似乎比重载所有6(!)丰富的比较更好地满足了我的需求.(但是,如果你依赖于"交换的论证"/反映的行为,你可以把它归结为"只是"4,但这导致并发症的净增加,在我的拙见中.)
如果我只是超载,是否有任何不可预见的陷阱需要注意__cmp__?
我明白了<,<=,==等运营商也可以被重载用于其他目的,并且可以返回任何他们喜欢的对象.我不是在询问这种方法的优点,而是仅仅考虑使用这些运算符进行比较时的差异,这与它们对数字的意义相同.
更新:克里斯托弗指出,cmp正在消失3.x. 有没有其他方法可以使实施比较变得如上所述__cmp__?
我有一个包含以下详细信息的列表:
list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]
Run Code Online (Sandbox Code Playgroud)
现在,我想对此列表进行排序,以使值按以下顺序排列:
list1 = ["1", "2C", "36", "100A", "132", "302F", "342B"]
Run Code Online (Sandbox Code Playgroud)
只是list1.sort()显然没有给出正确的答案 - 它给出:
list1 = ["1", "100A", "132", "2C", "36", "302F", "342B"]
Run Code Online (Sandbox Code Playgroud)
我假设这是因为python直接将所有这些视为字符串.但是,我想根据它们的数值FIRST对它们进行排序,然后根据数字后面的字符对它们进行排序.
我该怎么办?
非常感谢 :)
我尝试编写一个小类,并希望根据重量对项目进行排序。提供了代码,
class Bird:
def __init__(self, weight):
# __weight for the private variable
self.__weight = weight
def weight(self):
return self.__weight
def __repr__(self):
return "Bird, weight = " + str(self.__weight)
if __name__ == '__main__':
# Create a list of Bird objects.
birds = []
birds.append(Bird(10))
birds.append(Bird(5))
birds.append(Bird(200))
# Sort the birds by their weights.
birds.sort(lambda b: b.weight())
# Display sorted birds.
for b in birds:
print(b)
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,我得到的错误堆栈Python TypeError: sort() takes no positional arguments。这里有什么问题?
如何对包含字符串数字和字母的列表进行排序,即先对数字进行排序,然后再按字母顺序对字母进行排序?
my_list = ["10","2","1","5","a","b","c"]
disable_sorted_list
"1","2","5","10","a","b","c"
Run Code Online (Sandbox Code Playgroud)