如何在字典中获得与一个值相关联的各种信息?

2024-06-01 06:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:请查看底部,以便更清楚地了解我在做什么!你知道吗

举个例子,假设我有三辆车的信息:

Car One
500hp
180mph
15mpg

Car Two
380hp
140mph
24mpg

Car Three
450hp
170mph
20mpg

我想把它放在字典里,或者别的什么东西里,这样我就可以很容易地通过函数访问它。你知道吗

def fuel_eco(car):
   return("The fuel economy for %s is %s" % (car, mpg))
def top_speed(car):
   return("The top speed for %s is %s" % (car, speed))
def horsepower(car):
   return("The horsepower for %s is %s" % (car, hp))

基本上有一个带有一些函数的模块和一个列表/字典/任何信息,然后有另一个脚本,询问他们想查看哪辆车的信息,以及他们想知道什么信息。你知道吗

import carstats

car = input("What car do you want to find out about?")
stat = input("What information do you want to know?")
getStat = getattr (carstats, stat)
print(getStat(car))

如何在字典中存储这三辆车的信息(如果我添加了它们,还会存储更多),以便检索信息?你知道吗


好的,这些是我正在处理的实际文件:

一号文件是asoiaf.py公司地址:

def sigil (house):
 """
 Function to return a description of the sigil of a specified Great House.
 Takes one argument, the name of the House.
 """
 house = house.lower ()
 if house == "stark":
  sigil = "a grey direwolf on a white field."
 elif house == "lannister":
  sigil = "a golden lion rampant on a crimson field."
 elif house == "targaryen":
  sigil = "a red three-headed dragon on a black field."
 else:
  sigil = "Unknown"
 house = str(house[0].upper()) + str(house[1:len(house)])
 return("The sigil for House %s is %s" % (house, sigil))


def motto (house):
 """
 Function to return the family motto of a specified Great House.
 Takes one argument, the name of the House.
 """
 house = house.lower ()
 if house == "stark":
  motto = "Winter is coming!"
 elif house == "lannister":
  motto = "Hear me roar!"
 elif house == "targaryen":
  motto = "Fire and blood!"
 else:
  motto = "Unknown"
 house = str(house[0].upper()) + str(house[1:len(house)])
 return("The motto for House %s is:  %s" % (house, motto))

第二个文件是百科全书.py地址:

import asoiaf
#import sl4a

#droid = sl4a.Android ()
#sound = input ("Would you like to turn on sound?")
info = "yes"

while info == "yes":
 #if sound == "yes":
 # droid.ttsSpeak ("What house do you want to learn about?")
 house = input ("What house do you want to learn about?")
 house = str(house[0].upper()) + str(house[1:len(house)])
 #if sound == "yes":
 # droid.ttsSpeak  ("What do you want to know about House %s?" % house)
 area = input ("What do you want to know about House %s?" % house)
 getArea = getattr (asoiaf, area)
 #if sound == "yes":
 # droid.ttsSpeak (getArea (house))
 print (getArea (house))
 #if sound == "yes":
 # droid.ttsSpeak  ("Would you like to continue learning?")
 info = input ("Would you like to continue learning?")
 if info == "no":
  print ("Goodbye!")

在上一段代码中你会看到很多注释,因为我不得不注释掉我手机上的TTS,因为现在大多数人都不使用Android。如您所见,我在函数中使用IF、ELIF和ELSE,我只是想看看是否有更简单的方法。我很抱歉,如果这让人困惑的话。你知道吗


Tags: toyou信息inputreturnifiscar
3条回答

创建类应该是最好的方法:

class Car: # define the class

    def __init__(self, name, speed, hp, mpg):
        # This is the constructor. The self parameter is handled by python,
        # You have to put it. it represents the object itself
        self.name = name
        self.speed = speed
        self.hp = hp
        self.mpg = hp
        # This bind the parameters to the object
        # So you can access them throught the object            

然后可以这样使用对象:

my_car1 = Car('Car One', 180, 500, 15)
my_car1.speed # Will return 180

关于__init__名称,它必须是这个名称,所有构造函数都有这个名称(这就是Python知道它是类构造函数的方式)。__init__方法在调用Car('car one', 180, 500, 15)时被调用。你必须输入self参数,Python来处理它。 可以向类中添加其他函数,如

def top_speed(self):
    return 'The top speed is {}'.format(self.speed)

然后你只需要做我的车1.topspeed() 在类中定义的每个函数中,self必须是第一个参数(除了classmethod或staticmethods等少数情况)。显然,topseed函数只有在class Car:块中创建时才起作用。你知道吗

我建议您应该阅读更多关于Python中的面向对象编程(OOP)的内容。只要googleooppython,你就会有很多严肃的资源来解释如何创建类以及如何使用它们。你知道吗

这个official python classes tutorial应该对你理解这个概念有很大帮助。你知道吗

编辑:

关于访问其他脚本中的类。很简单:

假设您将上面的代码保存在汽车.py文件。只需将该文件与其他脚本放在同一文件夹中,然后在其他脚本中执行以下操作:

from car import Car # car is the name of the .py file, Car is the class you want to import
name = input('Car name: ')
speed = int(input('Car speed: ')) # input return a string, you have to cast to an integer to have a number
hp = int(input('Car hp: '))
mpg = int(input('Car mpg : '))
my_car = Car(name,speed,hp,mpg) # Then you just create a Car Object with the data you fetched from a user.
stuff = my_car.speed * my_car.hp # An example of how to use your class
print('The given car have {} mph top speed and have {} horsepower'.format(my_car.speed,my_car.hp))

您必须理解的是,类是某种格式化的数据类型。创建汽车类时,定义如何创建汽车对象。每次你调用Car(…),你实际上创建了一个这样的对象,你在这个对象中输入的值就是你想输入的值。它可以是随机数,用户输入,甚至网络获取的数据。您可以根据需要使用此对象。你知道吗

编辑2:

给你的密码。创建类会改变一些事情。让我们举个例子。你知道吗

文件1房子.py地址:

class House: # defining a house class
    def __init__(self,name, sigil, motto):
        self.name = name
        self.sigil = sigil
        self.moto = motto

 # Then, in the same file, you create your houses.
 starks =  House('starks','grey direwolf on a white field','Winter is coming!')
 lannisters = House('lannisters', 'a golden lion rampant on a crimson field', 'Hear me roar!')
 # let's skip targaryen, it's the same way...
 unknown_house = House('unknown','unknown','unknow')
 houses = [starks, lannisters]
 def get_house(name):
     for house in houses:
         if house.name == name:
             return house
     return unknow_house # if no house match, return unknow

然后在你的第二个文件里。你只要明白:

import houses
house_wanted = input('What house do you want to know about?')
my_house = houses.get_house(house_wanted)
print('this is the house {}; Sigil {} and motto {}'.format(my_house.name, my_house.sigil, my_house.motto))

如果你打算在biggers上工作。你应该看看枚举。那会符合你的要求。你知道吗

如果要获得精确的属性,可以这样做:

import houses
house_wanted = input('What house do you want to know about?')
my_house = houses.get_house(house_wanted)
attr= input('What do you want to know about that house?')
print(getattr(my_house,attr.lower()))

注意,如果您调用不存在的attr(比如foo),最后一件事将引发一个错误。你知道吗

您可以创建一个名为car的类,它具有您想要的任何属性! 下面是一个关于如何做到这一点的很棒的教程:class tutorial 我现在在路上,但是如果你有麻烦,请告诉我,这样我可以写一些有用的代码。。。你知道吗

有许多方法可以解决您在问题文本中描述的更广泛的问题(如何存储有关对象的多条信息的问题)。也许是一门好课。类比字典具有更好的健壮性。你知道吗

要回答摘要/标题中的特定问题:“如何使多个项与字典中的一个键相关联”-请使用字典作为值,如下所示:

car_info = {'CarOne': {'power': 500, 'speed': 180, 'mileage': 18},
            'CarTwo': {'power': 380, 'spead': 200, 'mileage': 10}
            }

print "Car Two has power %d mileage %d" % (car_info['CarTwo']['power'], car_info['CarTwo']['mileage'])

您可以看到,通过尝试访问“CarTwo”的“speed”,这并不是特别健壮。如果你仔细看你会发现,因为我故意在CarTwo的初始值上打错了,它根本没有速度,它有一个spead。类将捕获此错误,而字典不会。你知道吗

这并不是不使用词典的理由——只是在为你的特定案例做决定时需要注意的一点。你知道吗

相关问题 更多 >