簡體   English   中英

Python從字典列表列表中創建列表

[英]Python create list from a list of lists of dictionaries

我有一個list ,其中包含有關ZIP的信息(它們的位置,大小ect)的信息,該列表稱為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'}]

我需要創建一個名為hrefenclosures list ,該 enclosures list 以相同的順序包含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
href = [x[0]['href'] for x in enclosures]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM