python - 从python中的列表和字典的复杂列表中提取元素

标签 python list dictionary nested-lists

我有一个列表,其中包含许多代表纽约市地铁车辆的列表和字典:

[[{'arrival': {'time': 1506873749L},
   'departure': {'time': 1506873749L},
   'schedule_relationship': 0,
   'stop_id': u'B20S'},
  {'arrival': {'time': 1506873854L},
   'departure': {'time': 1506873854L},
   'schedule_relationship': 0,
   'stop_id': u'B21S'},
  {'arrival': {'time': 1506873989L},
   'departure': {'time': 1506873989L},
   'schedule_relationship': 0,
   'stop_id': u'B22S'},
  {'arrival': {'time': 1506874184L},
   'departure': {'time': 1506874184L},
   'schedule_relationship': 0,
   'stop_id': u'B23S'},
  {'arrival': {'time': 1506874469L},
   'departure': {'time': 1506874469L},
   'schedule_relationship': 0,
   'stop_id': u'D43S'}],
 [{'arrival': {'time': 1506873814L},
   'departure': {'time': 1506873814L},
   'schedule_relationship': 0,
   'stop_id': u'D10N'},
  {'arrival': {'time': 1506873877L},
   'departure': {'time': 1506873877L},
   'schedule_relationship': 0,
   'stop_id': u'D09N'},
  {'arrival': {'time': 1506873997L},
   'departure': {'time': 1506873997L},
   'schedule_relationship': 0,
   'stop_id': u'D08N'},
  {'arrival': {'time': 1506874087L},
   'departure': {'time': 1506874087L},
   'schedule_relationship': 0,
   'stop_id': u'D07N'},
  {'arrival': {'time': 1506874177L},
   'departure': {'time': 1506874177L},
   'schedule_relationship': 0,
   'stop_id': u'D06N'},
  {'arrival': {'time': 1506874267L},
   'departure': {'time': 1506874267L},
   'schedule_relationship': 0,
   'stop_id': u'D05N'},
  {'arrival': {'time': 1506874357L},
   'departure': {'time': 1506874357L},
   'schedule_relationship': 0,
   'stop_id': u'D04N'},
  {'arrival': {'time': 1506874477L},
   'departure': {'time': 1506874477L},
   'schedule_relationship': 0,
   'stop_id': u'D03N'},
  {'arrival': {'time': 1506874627L},
   'departure': {'time': 1506874627L},
   'schedule_relationship': 0,
   'stop_id': u'D01N'}]]

我正在尝试识别与特定 stop_id 关联的条目。例如,如果我正在搜索“D03N”,我想返回与之关联的整个条目:

 {'arrival': {'time': 1506874477L},
       'departure': {'time': 1506874477L},
       'schedule_relationship': 0,
       'stop_id': u'D03N'}

不幸的是,每当我尝试使用此答案中的建议时:Python list of dictionaries search 我以“TypeError: list indices must be integers, not str”错误消息结束。我不确定这是因为我没有正确实现该解决方案,还是因为该列表与原始问题中的列表相比相对复杂,所以该解决方案不适用。

有没有办法从这个列表中提取特定条目?

最佳答案

l = <your list>
[ i for i in sum(l,[]) if i['stop_id'] == 'D03N' ]

或更有效的方式

from itertools import chain
[ i for i in chain.from_iterable(l) if i['stop_id'] == 'D03N' ]

关于python - 从python中的列表和字典的复杂列表中提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46514274/

相关文章:

python - 如何找到 zip 文件中发送给我的不带扩展名的文件的 mimetype?

html - CSS 列表样式下拉菜单定位

python - 重新启动以循环迭代列表python3

c++ - 删除 C++ 映射中的指针

python - 为什么 Python 中没有 first(iterable) 内置函数?

python - 如何更改 JSON 文件中的嵌套值?

python将多行中的单词提取到1个列表中

ios - 比较两个字典值给我一个 NSInvalidArgumentException

c# - 从 app.config 配置部分将键值对读入字典

使用自定义名称创建 Python 动态函数