Wamlab - 4 months ago 19

Python Question

`collection = ["81851 19AJA01", "68158 17ARB03", "104837 20AAH02",`

I have a list that extends on like this and I would like to sort them based on the first 2 digits of the second part of each. I'm really rushed right now so some help would be nice.

I tried this and it didn't work. I'm not doing this for a class I'd really appropriate some help

`for x in collection:`

counter = 0

i=0

for y in len(str(x)):

if (x[i] == '1'):

counter == 1

elif (x[i] == '2'):

counter == 2

elif x[i] == '0' and counter == 2:

counter = 2

elif x[i] == '9' and counter == 1:

counter = 3

elif x[i] == '8' and counter == 1:

counter = 4

elif x[i] == '7' and counter == 1:

counter = 5

i = i + 1

if (counter==2):

freshmen.append(x)

elif (counter==3):

sophomores.append(x)

elif (counter==4):

juniors.append(x)

elif (counter==5):

seniors.append(x)

Answer

Use the `key`

function to define a custom sorting rule:

```
In [1]: collection = ["81851 19AJA01", "68158 17ARB03", "104837 20AAH02"]
In [2]: sorted(collection, key=lambda x: int(x.split()[1][:2]))
Out[2]: ['68158 17ARB03', '81851 19AJA01', '104837 20AAH02']
```