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

时间:2014-07-02 13:15:03

标签: python list python-3.x python-2.x

我有一个list,其中包含有关ZIP的信息(位置,大小等),名为enclosures

使用以下代码创建列表:

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 list项,顺序相同

以下尝试失败。

>>> 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

1 个答案:

答案 0 :(得分:3)

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