【问题标题】:slices in list of dictionaries [duplicate]字典列表中的切片[重复]
【发布时间】:2013-06-20 00:37:39
【问题描述】:

是否有更快/更“pythonic”的方式来访问与字典列表中的单个键关联的值,而不是循环遍历它(如here 所示)?我正在寻找类似listDict[:]['id'] 的东西来获取值列表,但我得到了错误list indices must be integers, not str,即使listDict[0]['id'] 工作得很好。

更新 - 后续问题: 如果键的值本身也是一个列表,而我只对获取它的前 10 个元素感兴趣怎么办?

当使用列表解析时,很容易做到[dic['id'][:10] for dic in listDict],但是当使用itemgetter 时呢? map(itemgetter('id')[:10], listDict) 似乎不起作用。

我正在询问一种快速获取访问权限的方法,因为我有一个庞大的字典列表,并且我认为对于字典列表,我可以获得与 numpy 数组相同的行为(比如切片只是原始数组的视图) .我想知道 python 是否有任何方法可以利用列表中的所有字典具有相同大小的事实来使用快速跨步内存访问和一次复制大块数据而不将中间表示作为列表列表。

谢谢!

【问题讨论】:

  • 对不起,这是您给出的链接问题的副本,所有相同的答案都在那里
  • 我知道该问题的答案,如果有任何其他替代方案,我很感兴趣。
  • 最pythonic和最快的解决方案是那里接受的答案
  • 我最终从中制作了一个 numpy 数组,但我不知道是否预先分配它并循环遍历字典并将数据复制到相应的行,或者使用列表理解和numpy.asarray() .

标签: python list dictionary slice


【解决方案1】:

不,你不能在这里做这样的切片。您已经遍历整个列表并从每个字典中获取项目。

使用列表推导:

[dic['id'] for dic in listDict]

operator.itemgetter:

>>> from operator import itemgetter
>>> map(itemgetter('id'), listDict)

时间比较:

>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] *100

>>> %timeit [dic['id'] for dic in listDict]
10000 loops, best of 3: 50.8 us per loop
>>> %timeit map(itemgetter('id'), listDict)
10000 loops, best of 3: 42.7 us per loop

>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}]*1000

>>> %timeit [dic['id'] for dic in listDict]
1000 loops, best of 3: 446 us per loop
>>> %timeit map(itemgetter('id'), listDict)
1000 loops, best of 3: 440 us per loop

>>> listDict = [{'id':1,'other':2},{'id':3,'other':4},{'id':5,'other':6}] *10**5

>>> %timeit [dic['id'] for dic in listDict]
10 loops, best of 3: 50.7 ms per loop
>>> %timeit map(itemgetter('id'), listDict)
10 loops, best of 3: 45.6 ms per loop

【讨论】:

  • map itemgetter 比您的第一个给定解决方案更慢且更丑
  • @jamylak 结果更快。
  • 不在小名单上,差异可以忽略不计
猜你喜欢
  • 1970-01-01
  • 2021-09-14
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2023-03-28
  • 2022-01-03
  • 2019-04-30
相关资源
最近更新 更多