Home > OS >  unsort a list to get it back the way it was
unsort a list to get it back the way it was

Time:11-18

I want to unsort a list. For you to understand:

list1 = ["Hi", "Whats up this Morning" "Hello", "Good Morning"]

new_list = sorted(list1, key=len, reverse=True)

["Whats up this Morning", "Good Morning", "Hello", "Hi"]

And know it should go back exactly in the same way it was in the beginning

["Hi", "Whats up this Morning", "Hello", "Good Morning"]

Anyone knows the answer?

CodePudding user response:

Getting to it right out of the gate, list1 never changes, so as long as you retain this object in memory you will always have a way to refer to the original list, since it's unchanged. new_list is a new object, and the absolute simplest thing you can do is keep both these objects and refer to them at will.

Taking your question from a conceptual standpoint: is there a way to keep track of the original order based on the new object? If you absolutely needed to revert to the original order based only on the new_list, you could first index the list using enumerate(). This tracks the order of your object like so: (0, 'Hi') (1, 'Whats up this Morning') (2, 'Hello') (3, 'Good Morning'). Then, you can sort by the length of the second object in each tuple (the original string) with new_list = sorted(enumerate(list1), key=lambda x: len(x[1]), reverse=True). Finally, you can extract your original list (as a tuple) with words, indices = zip(*new_list). Then reversing back to the string is quite simple, see the below example:

list1 = ["Hi", "Whats up this Morning", "Hello", "Good Morning"]
# Pack indices and sort
new_list = sorted(enumerate(list1), key=lambda x: len(x[1]), reverse=True)

# Unpack sorted strings and old indices
indices, words = zip(*new_list)
print(words)  # ('Whats up this Morning', 'Good Morning', 'Hello', 'Hi')
print(indices)  # (1, 3, 2, 0)

# Reverse the sorting based on the old indices
original_list_packed = sorted(zip(indices, words))
print(original_list_packed)  # [(0, 'Hi'), (1, 'Whats up this Morning'), (2, 'Hello'), (3, 'Good Morning')]
_, original_list = zip(*original_list_packed)
print(original_list)  # ('Hi', 'Whats up this Morning', 'Hello', 'Good Morning')

CodePudding user response:

Our list is:

list1 = ["Hi", "Whats up this Morning" "Hello", "Good Morning"]

And the new list is:

new_list = sorted(list1, key=len, reverse=True)

We sort list1and store original keys of new_list

list_keys = sorted(range(len(list1)), key=lambda k: list1[k], reverse=True)
>>> [1, 0, 2]

Ant get back the fist list:

list3 = [None] * len(list1)
for indx in range(len(list_keys)):
    list3[indx] = list1[indx]

Output

>>> list3
>>> ['Hi', 'Whats up this MorningHello', 'Good Morning']
  • Related