【问题标题】:Access "Actions" object in a list using enumerate() in python在 python 中使用 enumerate() 访问列表中的“Actions”对象
【发布时间】:2019-11-12 16:04:07
【问题描述】:
# Python program to illustrate 
# enumerate function 
l1 = [{'Actions':("eat","sleep","repeat"), 'members':("1028", "jeram", "chilaw")}] 
s1 = "geek"

# creating enumerate objects 
obj1 = enumerate(l1) 
obj2 = enumerate(s1) 

print "Return type:",type(obj1) 
print list(enumerate(l1['Actions'])) 

# changing start index to 2 from 0 
print list(enumerate(s1,2)) 

需要使用 enumerate 函数在 (l)1 列表中打印“Action”对象。但发生错误,所述列表索引必须是整数,而不是 str。帮我解决这个问题。

我得到的错误是,

Traceback (most recent call last):
  File "/home/25b7a4de08d5472b64b462006452cf1f.py", line 11, in <module>
    print list(enumerate(l1['Actions'])) 
TypeError: list indices must be integers, not str

请给我任何解决方案。在此先感谢。

【问题讨论】:

    标签: python indexing enumerate


    【解决方案1】:

    您没有访问字典;索引您的列表,获取字典。

    用途:

    list(enumerate(l1[0]['Actions']))
    

    代替:

    list(enumerate(l1['Actions']))
    

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 2010-10-25
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      相关资源
      最近更新 更多