gpt4 book ai didi

python 3 : How do I sort both parallel lists?

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:38 28 4
gpt4 key购买 nike

我需要能够按升序或降序对员工姓名及其年龄的平行列表进行排序。我可以得到一个列表进行排序,但我不知道如何得到第二个列表来分别将名字与他们的年龄配对。例如,我需要它看起来像这样。

Phil is 20 years old
Mike is 23 years old
Jenny is 38 years old
Jim is 65 years old

但它看起来像这样。

['Jim', 'Jenny', 'Phil', 'Mike'] is [20, 23, 38, 66] years old.

到目前为止,这是我的代码。

def get_name():
employee_name = input("Enter the employee's name: ")
return employee_name

def get_age():
while True:
try:
employee_age = int(input("Enter the employee's age: "))
return employee_age
except ValueError:
print("Please enter a valid number")

def main():
num_age = []
string_name = []

print("This program sorts employee's by age.")

while True:
try:
num_employees = int(input("Enter the number of employee's who are being evaluated: "))
break
except ValueError:
print("Please enter a valid number.")

while True:
for i in range(num_employees):
num_employees -= 1
name = get_name()
string_name += [name]

age = get_age()
num_age += [age]

if num_employees == 0:
print(str(sorted(string_name)) + " is " + (str(sorted(num_age))) + " years old.")
break

main()

最佳答案

解决此问题的一种经典方法是使用 Python 的内置 zip 函数将列表连接在一起,然后对数据进行排序。排序完成后,您可以返回到原始(但已排序)列表:

list1 = ['Jim', 'Jenny', 'Phil', 'Mike']
list2 = [65, 38, 20, 23]
list2, list1 = (list(t) for t in zip(*sorted(zip(list2, list1))))

关于 python 3 : How do I sort both parallel lists?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33351253/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com