繁体   English   中英

遍历列表(Python)

[英]Iterating through list (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)

使用key函数定义自定义排序规则:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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