【问题标题】:How to Access a List through a key?如何通过密钥访问列表?
【发布时间】:2015-08-02 12:43:20
【问题描述】:

我有一个程序,它的保存文件中充满了列表。它通过制作列表来加载项目。它也从文件中获取名称。由于我无法“解开”字符串,所以我将名称作为键。我的问题是在您使用完该程序后重新保存列表。我似乎无法访问列表中的内容以将它们写入文件。我有另一个带有键的列表,因此我可以访问名称。

ListKey = {1:'Food', 2:'Veggie'}
List={'Food':['apple','pear','grape'], 'Veggies':['carrot','Spinach','Potato']}

file.write(ListKey[1]) #works fine
currentList=ListKey[1]
file.write(List[currentList[1]]) #Doesn't Work

当我尝试执行上面的代码时,我得到一个关键错误,我知道它试图在 food 中写 'o'。有没有办法解决这个问题?

【问题讨论】:

  • 当您说要“访问列表中的内容”时,您的意思是在List? Listdictionary。你到底想把什么写入文件?

标签: python string list dictionary key


【解决方案1】:

您似乎正在尝试访问密钥对中的值。试试:

List[currentList][0] to access 'apple'
List[currentList][1] to access 'pear'

等等……

或者,如果你想要所有的值,它看起来像

List[currentList]  or 
List['Food']

希望这对您有所帮助,只是您如何访问里面的列表的语法。

编辑: https://docs.python.org/2/tutorial/datastructures.html#nested-list-comprehensions (添加了数据结构文档的链接)

【讨论】:

    【解决方案2】:

    currentList[1] 只是值o,使用:

    file.write(List[currentList])
    

    【讨论】:

    • ListKey 而不是List
    【解决方案3】:

    ListKey = {1:'Food', 2:'Veggie'} List={'Food':['apple','pear','grape'], 'Veggies': ['carrot','Spinach','Potato']} currentList = ListKey[1] #'Food' currentList[1] # 'o'

    您实际上是在对字符串“Food”进行索引。因此 currentList[1] 是'o'。由于 List 没有键“o”,因此您会遇到键错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2014-02-19
      • 2018-11-19
      • 2016-01-07
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      相关资源
      最近更新 更多