簡體   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