【发布时间】:2015-06-12 20:22:31
【问题描述】:
我正在尝试使用 Python 的 sorted 函数对列表进行排序。在 Python 3 中,cmp 关键字参数已被删除。不幸的是,我似乎无法使用 key 关键字参数来实现我的算法,因为我需要两个对象才能比较数据。
排序数据示例
59 59
59 3 1 1
59 4 3 3
61 1
61 10
61 237
61 1 1 1
比较函数
NUM_RE = re.compile("[\d]+")
def compare(x, y):
# Aggregate our data into integer arrays
x_result = [int(x) for x in NUM_RE.findall(x)]
y_result = [int(y) for y in NUM_RE.findall(y)]
# Return if there is a non-zero difference in the first element
statement_diff = x_result[0] - y_result[0]
if statement_diff != 0:
return statement_diff
# Return if there is a non-zero difference between the lengths
length_diff = len(x_result) - len(y_result)
if length_diff != 0:
return length_diff
# len(x_result) == len(y_result)
# Iterate over each item and return if there is a difference
for i in range(1, len(x_result)):
result = x_result[i] - y_result[i]
if result != 0:
return result
# Results are the same
return 0
对这些数据进行排序的最佳方法是什么?我是否应该创建一个实现__eq___、__gt__、__lt__ 等函数的“包装器对象”,以便可以使用默认排序函数?或者标准 Python API 中是否包含另一个函数来完成 sorted 的原始行为?
【问题讨论】:
-
你到底想做什么?我感觉它可以简化很多,
min(x_result.groups(), y_result.groups())如何与范围一起工作? -
不也是
NUM_RE.findall没有群组吗? -
您提供的比较功能不正确。没有
find_all方法,findall返回一个列表——不是一个匹配对象,正如您在这里所期望的那样。您能否提供一个有效的比较功能来显示您实际寻找的内容?如果比较函数实际上产生了一致的顺序,那么应该可以将其重写为key函数。 -
@senderle 抱歉,我已经修复了比较功能
标签: python sorting python-3.x