gpt4 book ai didi

Python 从字典列表的列表中创建列表

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:10 25 4
gpt4 key购买 nike

我有一个列表,它在名为enclosures 的列表中包含有关 ZIP(它们的位置、大小等)的信息。

列表是用这段代码创建的:

for item in g.entries:
enclosure = [l for l in item["links"] if l["rel"] == "enclosure"]
if(len(enclosure)>0):
enclosures.append(enclosure)

enclosures 列表中的每一项都具有以下格式:

>>> enclosures[0]
[{'type': 'application/zip', 'rel': 'enclosure', 'length': '57648', 'href': 'http://www.sec.gov/Archives/edgar/data/37748/000003774810000025/0000037748-10-000025-xbrl.zip'}]

或者另一个例子...

>>> enclosures[45]
[{'type': 'application/zip', 'rel': 'enclosure', 'length': '107907', 'href': 'http://www.sec.gov/Archives/edgar/data/1385157/000104746910004400/0001047469-10-004400-xbrl.zip'}]

我需要的是创建一个名为href 的列表,其中包含附件列表 中的每个href以相同的顺序

以下这些尝试都失败了。

>>> enclosures[46]["href"]
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
enclosures[46]["href"]
TypeError: list indices must be integers, not str

>>> enclosures[46][4]
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
enclosures[46][4]
IndexError: list index out of range

编辑

亲爱的timgeb

我有这样的结果:

>>> href = [x['href'] for x in enclosures]
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
href = [x['href'] for x in enclosures]
File "<pyshell#75>", line 1, in <listcomp>
href = [x['href'] for x in enclosures]
TypeError: list indices must be integers, not str

最佳答案

href = [x[0]['href'] for x in enclosures]

关于Python 从字典列表的列表中创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24532126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com