如何在python中对多个列表进行排序

我正在尝试根据年龄列表从上到下对多个列表进行排序。但这总是给我错误。

def age(last,name,birthday):
ages=['32','21','35']
names=['Mattie','Meaghan','Gladys']
lasts=['Poquette','Garufi','Rim']
ctr=1
"""I tried the line below but it gives me error! error message: ages,lasts,names = zip(*sorted(zip(ages,lasts,names)))
  ValueError: not enough values to unpack (expected 3, got 0)
   """
 ages,lasts,names = zip(*sorted(zip(ages,lasts,names)))

for bday in birthday:
   my_date = bday
   b_date = datetime.strptime(my_date, '%m/%d/%Y')
   age=("%d" % ((datetime.today() - b_date).days / 365))
   ages.append(age)
for l in last:
   lasts.append(l)
for n in name:
    names.append(n)
# Iwant this to be sorted by age
for a,l,n in zip(ages,lasts,names):
    print(f"{ctr} Employee name {l}, {n} Age:{a}") 
    ctr+=1
评论
夜~太美
夜~太美

尝试这个

for i in range(len(ages)): 
    # Find the minimum element in remaining  
    # unsorted array 
    min_idx = i 
    for j in range(i+1, len(ages)): 
        if ages[min_idx] > ages[j]: 
            min_idx = j 

    # Swap the found minimum element with  
    # the first element         
    # and also remining data
    ages[i], ages[min_idx] = ages[min_idx], ages[i] 
    names[i], names[min_idx] = names[min_idx], names[i] 
    lasts[i], lasts[min_idx] = lasts[min_idx], lasts[i] 

# Hence data is sorted by age
点赞
评论
联盟
联盟

尝试将您的数据存储在字典中,例如age作为键,以及将名称和last作为元素的列表。那么您就可以轻松地按年龄排序。

字典: 关键元素 年龄-> [名字,姓氏]

点赞
评论
bquos
bquos

我没有这个解决方案的问题

ages=['32','21','35']
names=['Mattie','Meaghan','Gladys']
lasts=['Poquette','Garufi','Rim']

ages,lasts,names = zip(*sorted(zip(ages,lasts,names)))
print(ages,lasts,names)

输出:

('21','32','35')('Garufi','Poquette','Rim')('Meaghan','Mattie','Gladys')

但是我认识到,如果我首先将zip对象保存在一个变量中,然后将其打印为列表,然后再使用该zip对象进行排序,那么我将得到与您相同的错误。

z = zip(ages,lasts,names)
print(list(z))
ages,lasts,names = zip(*sorted(z))
print(ages,lasts,names)

输出:

[(''21','Garufi','Meaghan'),('32','Poquette','Mattie'),('35','Rim','Gladys')]      追溯(最近一次通话):      文件“ c:/ Users / * / Desktop / Test.py”,第9行      年龄,姓氏,名称= zip(* sorted(z))      ValueError:没有足够的值可解包(预期3,得到0)

也许这会对您有所帮助。

点赞
评论