Andrea Ianni
Andrea Ianni

Reputation: 839

Setting a proper ordering of a list

I have two lists like:

>> K = 3
>> ll_G = ['GIO_%s' % (k) for k in range(K)]
>> ll_P = ['PAX_%s' % (k) for k in range(K)]
>> ll_GP = ll_G + ll_P
>> ll_GP
['GIO_0', 'GIO_1', 'GIO_2', 'PAX_0', 'PAX_1', 'PAX_2']

I want to order the final list such to have:

['GIO_0', 'PAX_0', 'GIO_1', 'PAX_1', 'GIO_2',  'PAX_2']

I guess it could be quite simple: how can I do?

Upvotes: 1

Views: 33

Answers (4)

m0nhawk
m0nhawk

Reputation: 24168

You can sort by last symbol:

sorted(abc, key=lambda x: int(re.findall(r'\d+$', x)[0]))

The int(re.findall(r'\d+$', x)[0]) takes the numbers on the end and use their integer representation as a key for comparison.

Upvotes: 1

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

I have two lists like

Why not just build the desired list directly?

>>> K = 3
>>> [s % k for k in range(K) for s in ('GIO_%s', 'PAX_%s')]
['GIO_0', 'PAX_0', 'GIO_1', 'PAX_1', 'GIO_2', 'PAX_2']

Upvotes: 2

Sunny Aggarwal
Sunny Aggarwal

Reputation: 81

You'd need to loop on two base lists and add elements to final list in alternating fashion i.e something like this

for i in range(len(11_G)):
    11_GP.append(11_G[i])
    11_GP.append(11_P[i])

Upvotes: 2

DMe
DMe

Reputation: 7826

You could do the following:

ll_GP.sort(key = lambda x: x[-1])

Upvotes: 2

Related Questions