简体   繁体   中英

Iterating through list (Python)

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.

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

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)

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM