Home > OS >  Python change index for value array
Python change index for value array

Time:08-31

In python I have the following array:

['75920-c1-u1 .pdf', '75920-c1-u2 .pdf', '75920-c1-u3 .pdf', '75920-c1-u4 .pdf', '75920-c1-u5 .pdf' , '75920-c1.pdf']

I would like to make the element: 75920-c1.pdf be on the index 0 and after it the rest should follow, so 75920-c1-u1 .pdf, 75920-c1-u2 .pdf etc...

I can't even manage to do this...

CodePudding user response:

    ls = ['75920-c1-u1 .pdf', '75920-c1-u2 .pdf', '75920-c1-u3 .pdf', '75920-c1-u4 .pdf', '75920-c1-u5 .pdf' , '75920-c1.pdf']
    ls.sort(key=lambda s:(len(s),s))
    # ls = ['75920-c1.pdf', '75920-c1-u1 .pdf', '75920-c1-u2 .pdf', '75920-c1-u3 .pdf', '75920-c1-u4 .pdf', '75920-c1-u5 .pdf']

CodePudding user response:

You need to (simple, but not necessarily the solution for large lists) slice your list or write a sort function.

Slicing could be done by (I assume you called it "array" bc it is a np array?) list(NP_ARRAY)[-1] list(NP_ARRAY)[:-1].

A list named "name" is sliced from a to b by name[a:b]. The - means count from the end.

A sort function should split the string after '75920-c1' and sort from there.

CodePudding user response:

just pop the value and insert it in the first index here is the code

a= ['75920-c1-u1 .pdf', '75920-c1-u2 .pdf', '75920-c1-u3 .pdf', '75920-c1-u4 .pdf', '75920-c1-u5 .pdf' , '75920-c1.pdf']
p = a.pop()
a.insert(0,p)

Hope it helps :)

  • Related