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

时间:2015-05-18 15:06:53

标签: python dictionary

编辑:检查底部,以便更清楚地了解我的所作所为,请!

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

Car One
500hp
180mph
15mpg

Car Two
380hp
140mph
24mpg

Car Three
450hp
170mph
20mpg

我想把它放在字典或SOMETHING中,以便我可以通过函数轻松访问它。

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))

第二个文件是encyclopedia.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,我只是想看看是否有更简单的方法。如果它是混乱的,我道歉。

3 个答案:

答案 0 :(得分:2)

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

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)

然后你只需要做my_car1.topspeed() 在类中定义的每个函数中,self必须是第一个参数(除了一些罕见的情况,例如classmethod或staticmethods)。显然,topseed函数只有在class Car:块中创建它才有效。

我建议你在Python中阅读更多关于面向对象编程(OOP)的内容。只是google OOP python,你会有很多严肃的资源来解释你如何创建类以及如何使用它们。

这个official python classes tutorial可以帮助你理解这个概念。

编辑:

关于在其他脚本中访问该类。这很简单:

假设您将上面的代码保存在car.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))

您必须了解的是,Class是某种格式化数据类型。创建Car类时,您将定义如何创建car对象。每次调用Car(...)时,实际上都会创建其中一个对象,放在对象中的值是您想要放置的值。它可以是随机数,用户输入甚至网络获取数据。您可以根据需要使用此对象。

编辑2:

鉴于你的代码。创建类会改变一些事情。我们举个例子。

档案1 houses.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上工作。你应该看看Enums。这可能符合你的要求。

如果您想获得精确属性,可以这样做:

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),最后一件事会引发错误。

答案 1 :(得分:1)

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

回答摘要/标题中的具体问题:"如何在字典中有一个与一个键相关联的项目" - 使用字典作为值,如下所示:

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"。如果仔细观察,你会发现,因为我在CarTwo的初始化程序中故意拼错,它根本没有速度,它有一个spead。类将捕获此错误,字典不会。

这不是不用字典做的理由 - 只是在决定你的特定情况时要注意的事情。

答案 2 :(得分:0)

您可以使用您想要的任何属性创建一个名为car的类! 以下是有关如何执行此操作的精彩教程:class tutorial 我现在正在路上,但如果你遇到麻烦,请告诉我,以便我可以写一些有用的代码......