我是python的新手,在练习时遇到问题。用户将首先输入人数。然后,他/她将输入姓名,然后输入生日。
例如,如果采用先进入3
,再进入John
再1/1
3意味着用户将进入3人的生日和名字和日期(格式:日/月)。然后我问他们排序升序出生日期。
例如,如果输入3
John
12/6
Betty
1/5
Mike
16/1
将输出
Mike 16/1
Betty 1/5
John 12/6
这是我手头上的东西,我只能想到将两个列表压缩到字典中。然后,我不知道如何进行下一步。
number = int(input())
a=[]
b=[]
for i in range(number):
m = input()
a.append(m)
n = input()
b.append(n)
dictionary = dict(zip(a,b))
print(dictionary)
您可以将其sorted
与自定义函数一起使用,然后再进行for
循环:
def sort_key(x):
return list(map(int, x[1].split('/')))[::-1]
res = sorted(dictionary.items(), key=sort_key)
for name, date in res:
print(name, date)
Mike 16/1
Betty 1/5
John 12/6
关键位是sort_key
函数,该函数被除以'/'
,将字符串转换为整数,并反转列表,因此月份优先于日期。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句