对于我的下面的代码,一切正常,但我试图将我的输出存储在列表中,我无法弄清楚如何这样做。我试图创建一个空列表并将输出附加到该列表但它不起作用。任何帮助都会很棒!
sample_photo_rep["photo"]["tags"]["tag"]
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
print [sample_tags_list['raw'].decode('utf-8')]
current output:
[u'Nature']
[u'Mist']
[u'Mountain']
correct output: [u'nature', u'mist', u'mountain']
答案 0 :(得分:1)
在每个循环中,您将打印包含单个元素的列表,即[u'Nature']
,[u'Mountain']
等。
如果你删除括号,即[sample_tags_list['raw'].decode('utf-8')]
到sample_tags_list['raw'].decode('utf-8')
,你应该只是得到字符串。
不确定为什么你的追加不起作用,
output = []
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
output.append(sample_tags_list['raw'].decode('utf-8'))
应该做的伎俩。列表理解将完成与@abccd的答案相同的事情;两者都给出相同的输出。
答案 1 :(得分:0)
您可以随时使用列表理解:
print [sample_tags_list['raw'].decode('utf-8') for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]]
代替您的for loop
。到目前为止,这仍然是最优选的方式。您可以查看pydoc以获取使用列表组合的简单示例。
答案 2 :(得分:0)
在代码顶部声明一个空列表,如下所示:
tags = []
然后,而不是在for loop
中将其打印出来,而不是将其附加到列表中:
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
tags.append([sample_tags_list['raw'].decode('utf-8')])
然后标签应为:
[u'nature', u'mist', u'mountain']
进一步阅读
有关附加到列表的信息:https://www.tutorialspoint.com/python/list_append.htm