繁体   English   中英

如何在python中将两个变量的内容转换为一个可调用的变量名?

[英]How do you turn the content of two variables into one callable variable name in python?

我试图获取一个变量以从列表中获取字符串(这是一个变量名称),然后我要调用该变量。

有一个列表,其中存储了很多变量名和一些其他变量。

    fruits = ["apple","orange","banana","blueberry"]

    apple = ["A red fruit","sort of ball"]
    orange = ["An orange fruit","a ball"]
    banana = ["A yellow fruit","a fruit"]
    blueberry = ["A blue fruit","a berry"]
    number = 3

我想从清单中得到具有“编号”的水果:

    print(fruits[number])

将会输出: banana

输出是预先存在的列表变量的名称,那么如何调用该列表中的项目?

我尝试这样做:

    print((fruits[number])[2])

我认为可能是这样的:

    print(banana[2])

并输出: a fruit

预先感谢您的帮助。

这是不可能的。 您可以得到的最接近的是使用字典,该字典基本上是从键到值的映射。 在您的情况下,字典将如下所示:

fruits = {
    "apple": ["A red fruit","sort of ball"],
    "orange" : ["An orange fruit","a ball"],
    "banana": ["A yellow fruit","a fruit"],
    "blueberry": ["A blue fruit","a berry"]
}

现在,你可以这样做print(fruits['banana'][1])它将打印a fruit ,因为fruits是一本字典, 'banana'在这本词典的关键,而fruits[banana]等于["A yellow fruit","a fruit"] 当您访问fruits['banana']索引1的元素时,它返回该列表的第二个元素,因为列表在Python中是0索引的,并且是一个字符串a fruit

您想要的被称为关联数组 ,在python中,这些被称为字典

fruitsDict = {}

fruitsDict["apple"] = ["A red fruit","sort of ball"]
fruitsDict["orange"] = ["An orange fruit","a ball"]
fruitsDict["banana"] = ["A yellow fruit","a fruit"]
fruitsDict["blueberry"] = ["A blue fruit","a berry"]

如果您想以字符串形式获取字典的键,则可以使用

for key, value in fruitsDict.items():
      print(key,value[1])

输出:

苹果球
橙色一个球
香蕉一种水果
蓝莓一浆果

单击此处以获取教程中的工作示例

随意使用变量不是一个好主意。 在这种情况下,处理您要执行的操作的最佳方法是使用“ dict”。 这是本机“键:值” python的数据结构。

您可以这样定义水果及其描述:

fruits = {'banana': ['A yellow fruit', 'a fruit'],
          'orange': ['An orange fruit', 'a ball'],
          ...
          ...}

然后,如果要打印某些水果的描述,则应使用其键:

fruit_to_print = 'banana'
print fruits[fruit_to_print]

运行时将输出:

[“黄色水果”,“一种水果”]

例如,如果要获取描述的第一项:

print fruits[fruit_to_print][0]

将输出:

黄色水果

字典并非旨在成为有序的结构 ,因此您不应该使用索引来调用它的值,但是如果您真的确定自己在做什么,则可以执行以下操作:

fruits = {'banana': ['A yellow fruit', 'a fruit'],
      'orange': ['An orange fruit', 'a ball']}
number = 1
desc_index = 0
# fruits.keys() returns an array of the key names.
description = fruits[fruits.keys()[number]][desc_index] 

print description

>>> A yellow fruit

请记住,添加或删除元素可能会更改其他所有元素的索引。

另一种方法是创建一个Fruit类并具有一个Fruit数组:

class Fruit:
  def __init__(self, name, description):
      self.name = name
      self.description = description

fruit1 = Fruit('banana', ['A yellow fruit', 'a fruit'])
fruit2 = Fruit('orange', ['An orange fruit', 'a ball'])

fruits = []
fruits.append(fruit1)
fruits.append(fruit2)

fruit = 1
description = 0

print fruits[fruit].description[description]

橙色水果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM