I am trying to sort a list using Python's sorted function. In Python 3 the cmp keyword argument was removed. Unfortunately it seems that I cannot implement my algorithm using the key keyword argument since I need both objects in order to compare the data.
Example Sorted Data
59 59
59 3 1 1
59 4 3 3
61 1
61 10
61 237
61 1 1 1
Compare Function
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
What is the best method for sorting this data? Should I create a "wrapper object" that implements the __eq___, __gt__, __lt__, etc functions so I can use the default sorting function? Or is there another function included in the standard Python API that accomplishes the original behavior of sorted?
min(x_result.groups(), y_result.groups())work with range?NUM_RE.findalland have no groups?find_allmethod, andfindallreturns a list -- not a match object, as you seem to expect here. Could you provide a working comparison function that shows what you're actually looking for? If the comparison function actually produces a consistent order, then it should be possible to rewrite it as akeyfunction.