0

I want to sort some items in a specific data structure, But I will try to generalize the problem I am stuck with

My input is a list that contains string items, I am expecting three items as in here, But it won't be necessarily three all the time. But even though I wanna sort it

My input contain either a=['BHR','BHT','BHZ'] or a=['BHN','BHE','BHZ'] Perhaps Instead of BH* we can expect anything but we only focus on the last letter. either it will be 'Z,R,T' pair or 'Z,N,E' pair, the process should be stopped if it is in any other combination.

The output should be in the order of. a=['Z','R','T'] or a=['Z','N','R'] The output should be like this in order-wise even though there is no three items in the list

def sorter(a):
    n=len(a)
    for i in np.arange(0,n):
        if (a[i].find('Z') == 1):
            a0=a[i]
            continue
        elif (a[i].find('R') == 1):
            a1=a[i]
            continue
        elif (a[i].find('T') == 1):
            a2=a[i]
            continue
    
    a[0]=a0
    a[1]=a1
    a[2]=a2

Can anyone help me to finish this code? or suggest me a simple and effective alternate method?

NB: I would like to save the items in individual variables a0,a1,a2 and combine them later.

2 Answers 2

2

So you have a ordering of Z, N, R, T in total.

a=['BHR','BHT','BHZ']
a.sort(key=lambda t: "ZNRT".find(t[-1]))
Sign up to request clarification or add additional context in comments.

1 Comment

I really appreciate your solution. but in my case, I would like to save the items in individual variables a0,a1,a2 and combine them later
1

Use sorted, Sort by Z, R, T.

a = ['BHR', 'BHT', 'BHZ', "21a"]
a = sorted(a, key=lambda t: "TRZ".find(t[-1]), reverse=True)

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.