0

I have a very big 2D array where the second elements are not unique. Something like this:

list = [ ['text43','value43'], 
         ['text23','value23'], 
         ['text12','value12'],
         ['text43','different_val_43'],
         ['text12','another_value12'], 
         ['text04','value04'], 
         ['text43','anohter_value43'] ]

I would like to sort it by the first element but not in alphabetical order, just in the order of appearance of first element. Desired output:

list = [ ['text43','value43'],
         ['text43','different_val_43'],
         ['text43','anohter_value43'],
         ['text23','value23'],
         ['text12','value12'],
         ['text12','another_value12'],
         ['text04','value04'] ]
4
  • 2
    sorted(list1, key=lambda x: -int(x[0][-2:])) ? Commented Nov 13, 2018 at 13:07
  • Hello @Birbal, you'll need to add some code that you have already tried to make work. Have you tried anything? Commented Nov 13, 2018 at 13:09
  • 3
    Do not use list as the variable name of a python list. @BearBrown 's answer looks right. Commented Nov 13, 2018 at 13:11
  • Thanks @CharlesLandau ...actually was just an example, I have not named it list. Commented Nov 13, 2018 at 13:51

2 Answers 2

3

You can use a custom sorting function that would return the index at which the first element of a sublist is first found, e.g.:

lst = [['text43','value43'],
       ['text23','value23'],
       ['text12','value12'],
       ['text43','different_val_43'],
       ['text12','another_value12'],
       ['text04','value04'],
       ['text43','anohter_value43']]

d = {}
for i, item in enumerate(lst):
    if item[0] not in d:
        d[item[0]] = i

lst.sort(key=lambda item: d[item[0]])
print(lst)

Output:

[['text43', 'value43'],
 ['text43', 'different_val_43'],
 ['text43', 'anohter_value43'],
 ['text23', 'value23'],
 ['text12', 'value12'],
 ['text12', 'another_value12'],
 ['text04', 'value04']]
Sign up to request clarification or add additional context in comments.

Comments

0

Look if this helps. Using sorted()

lst = [ ['text43','value43'], 
         ['text23','value23'], 
         ['text12','value12'],
         ['text43','different_val_43'],
         ['text12','another_value12'], 
         ['text04','value04'], 
         ['text43','anohter_value43'] ]

sorted(lst, reverse=True)

Output:

[['text43', 'value43'],
 ['text43', 'different_val_43'],
 ['text43', 'anohter_value43'],
 ['text23', 'value23'],
 ['text12', 'value12'],
 ['text12', 'another_value12'],
 ['text04', 'value04']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.