如何根据单词的值排列单词列表?

问题描述 投票:0回答:1
# to input the names of animals(max is 3 names)    
i=1
animals=[]
while i<=5:
    y=input('animal{}name'.format(i))
    animals.append(y)
    i+=1
    if y=='only':
        break
print('your animals are ',animals)
i=1
while i<=len(animals):
    weight1=int(input('weight for {}'.format(animals[0])))
    speed1=int(input('speed for {}'.format(animals[0])))
    food_consumption1=int(input('food consumption for{}'.format(animals[0])))
    i+=1
    if i>len(animals):
        break 
    weight2=int(input('weight for {}'.format(animals[1])))
    speed2=int(input('speed for {}'.format(animals[1])))
    food_consumption2=int(input('food consumption for{}'.format(animals[1])))
    i+=1
    if i>len(animals):
        break 
    weight3=int(input('weight for {}'.format(animals[2])))
    speed3=int(input('speed for {}'.format(animals[2])))
    food_consumption3=int(input('food consumption for{}'.format(animals[2])))
speed_list=[speed1,speed2,speed3] 
speed_list.sort(inverse=true)

现在在将动物的速度从高速到低速排列后,我需要一个代码来允许我从最快的动物到最慢的动物排列动物名称

python python-3.x
1个回答
1
投票
class Animal(object):
  def __init__(self, spec, name,weight, power, speed):
    self._spec=spec
    self._name=name
    self._weight=weight
    self._power=power
    self._speed = speed
  def get_speed(self):return self._speed
  def __str__(self):
    return ','.join([self._spec, self._name, str(self._weight),str(self._power),str(self._speed)])


animals_list = [
                Animal('mammal','bear',150,2.5,55), 
                Animal('mammal','dog',70,1.5,40),
                Animal('mammal','lion',260,3.5,65),
                Animal('mammal','horse',350,1,70),
                Animal('mammal','tiger',260,12,77)
              ]


new_animals_list = sorted(animals_list, key=lambda animal:animal.get_speed())
for each in new_animals_list:
  print str(each)
© www.soinside.com 2019 - 2024. All rights reserved.