Python从字典列表创建列表

2024-09-22 16:36:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个list,它包含了一个名为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的列表,其中包含enclosures list中的每个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

Tags: inmost列表forlineziplistfile