从列表中获取列表

时间:2019-11-18 15:43:35

标签: python list dictionary

我有以下内容的列表:

quake_list = [{'time': '2016-01-12T21:05:59.000Z',
               'location': {'latitude': 60.5079, 'longitude': -142.9635},
               'event': {'magnitude': 1.3, 'depth': 9.1},
               'type': 'earthquake',
               'status': 'reviewed'},
              {'time': '2016-01-12T21:02:24.760Z',
               'location': {'latitude': 38.7978325, 'longitude': -122.7196655},
               'event': {'magnitude': 1.0, 'depth': -0.77},
               'type': 'earthquake',
               'status': 'automatic'},
               ...]

另一件事,我需要过滤掉None条目 似乎该文件没有该值的条目。

这就是为什么我收到错误消息

  

TypeError:列表索引必须是整数或切片,而不是str

我需要创建一个列表,其中包含所有值:

magnitude = [1.3,1.0]

谢谢您的帮助。

2 个答案:

答案 0 :(得分:6)

您可以执行以下操作:

try {
  $Mysql->beginTransaction();
  $Mysql->processOder();
  $Redis->multi();         //start redis transaction
  $Redis->deductStock();
  $Redis->exec()           //redis commit
  $Mysql->commit();        //mysql commit
} catch (Exception $e)
  $Mysql->rollback();      //mysql rollback
  $Redis->discard();       //redis rollback
}

要仅在地震记录时记录震级,请使用:

>>> [d['event']['magnitude'] for d in quake_list]
[1.3, 1.0]

答案 1 :(得分:1)

mag_list = [quake['event']['magnitude'] for quake in quake_list]
print(mag_list)