迭代列表(Python)

时间:2016-09-30 01:11:58

标签: python

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

我有一个像这样扩展的列表,我想根据每个第二部分的前两位数对它们进行排序。我现在真的很急,所以一些帮助会很好。

我尝试过这个并没有用。我不是为了一堂课,我真的很适合帮助

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)

1 个答案:

答案 0 :(得分:3)

使用key function定义自定义排序规则:

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