I got some data and need to create a sorting mapping. The actual sorting is done by C code, which takes the integer list flt_neworder from my code. This is my current solution:
# Demo data
data = [
"Option A", # 0
"Option B", # 1
"Blabla", # 2
"Some text" # 3
]
class Item:
def __init__(self, label):
self.label = label
col = [Item(d) for d in data]
# Create sorting mapping
flt_neworder = [
x[1] for x in sorted(
zip(
[x[0] for x in sorted(enumerate(col), key=lambda x: x[1].label)],
range(len(col))
)
)
]
# Output: [1,2,0,3]
print(flt_neworder)
Desired output:
[1,2,0,3], not[2,0,1,3]!Position in
flt_neworder= original index of item incolInteger values = new positions
What are more efficient, or at least better readable solutions?
I successfully tested this one-liner:
tuple({k: i for i, (k, v) in enumerate(sorted(enumerate(data), key=operator.itemgetter(1)))}.values())
But it's still hard to read, and I believe I'm exploiting the fact that dicts are sorted in the CPython implementation...
Edit
Another solution I came up with:
flt_neworder = [None] * len(col)
for j, (_, i) in enumerate(sorted(zip((item.label for item in col), range(len(col))))): flt_neworder[i] = j
And another, but rather slow one:
flt_neworder = list(map(get(0), sorted(enumerate(sorted(enumerate(item.label for item in col), key=get(1))), key=get(1))))
Thanks to Ryan P for providing alternative solutions and a script for testing the timing!
I tested the solutions on a large dataset (1k unique strings, full script) with amazing differences in timing compared to Ryan's small set:
orig: 2.116799074272876
origmod: 2.118176033553482
orignew: 1.1691872433702883
orig3: 1.4400411206224817
orig4: 2.0643228139915664
rewrite: 26.06907118537356
rewriteop: 25.91357442379376
rewriteuniq: 10.783081019086694
The winner is orignew(), and rewriteuniq() turns out to be fast for small datasets, but not great for large ones.
old index -> new indexmapping, where the old index is the position in the resulting list, and the contained values are the new indices (0 = item will be moved to top).[1,2,0]means the first item in the data is supposed to end up in the middle (position 1), the second at the end (pos 2) and the third at the top (pos 0).