1
我想要定义一个类,它将从包含多个字典的列表中制作标记列表(请参阅下文),但是当我尝试使用时,会得到以下回溯。我不确定我做错了什么。任何意见,将不胜感激!使用复杂列表定义类时出现错误
File "file.py", line 415, in <module>
p = Photo(data)
File "file.py", line 395, in __init__
for d in p_d["photo"]["tags"]["tag"]["_content"]:
TypeError: list indices must be integers or slices, not str
当前代码:
class Photo :
def __init__(self,p_d) :
self.tags = []
for d in p_d["photo"]["tags"]["tag"]["_content"]:
self.tags.append(d)
return
p = Photo(data)
print(p)
“数据” 的内容看起来像 “照片选词” 中this post。下面是与标签部分的例子:
u'media':u'photo',
u'tags':{
u'tag':[
{
u'machine_tag':False,
u'_content':u'aerialview',
u'author':u'[email protected]',
u'raw':u'Aerial View',
u'authorname':u'Patrick Foto ;)',
u'id':u'59579247-33334692904-8319'
},
{
u'machine_tag':False,
u'_content':u'buildingexterior',
u'author':u'[email protected]',
u'raw':u'Building Exterior',
u'authorname':u'Patrick Foto ;)',
u'id':u'59579247-33334692904-1727027'
},
{
u'machine_tag':False,
u'_content':u'businessfinanceandindustry',
u'author':u'[email protected]',
u'raw':u'Business Finance and Industry',
u'authorname':u'Patrick Foto ;)',
u'id':u'59579247-33334692904-263370815'
},
我看到现在。如果我只想得到['_content']位,我应该怎么处理? – BothanSpy
问题是,列表中的每个项目都有一个“_content”。你想要哪一个?如果你只想要第一个,你可以做'[0] ['_ content']'。如果你想要所有这些,你需要添加一个for循环。 – Gribouillis
我想将它们全部返回到列表中。编辑:这是我在当前循环中试图做的。 – BothanSpy