代码之家  ›  专栏  ›  技术社区  ›  Dennis Williamson

计算字典列表中的条目:for循环与map列表理解(itemgetter)

  •  4
  • Dennis Williamson  · 技术社区  · 16 年前

    在我编写的Python程序中,我比较了 for 循环和增量变量与列表理解 map(itemgetter) len() 在计算列表中的词典条目时。使用每个方法所需的时间相同。我做错什么了还是有更好的方法?

    这是一个大大简化和缩短的数据结构:

    list = [
      {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'biscuits and gravy'},
      {'key1': False, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'peaches and cream'},
      {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': False, 'filenotfound': 'Abbott and Costello'},
      {'key1': False, 'dontcare': False, 'ignoreme': True, 'key2': False, 'filenotfound': 'over and under'},
      {'key1': True, 'dontcare': True, 'ignoreme': False, 'key2': True, 'filenotfound': 'Scotch and... well... neat, thanks'}
    ]
    

    这是你的名字 对于

    #!/usr/bin/env python
    # Python 2.6
    # count the entries where key1 is True
    # keep a separate count for the subset that also have key2 True
    
    key1 = key2 = 0
    for dictionary in list:
        if dictionary["key1"]:
            key1 += 1
            if dictionary["key2"]:
                key2 += 1
    print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2)
    

    以上数据的输出:

    Counts: key1: 3, subset key2: 2
    

    #!/usr/bin/env python
    # Python 2.6
    # count the entries where key1 is True
    # keep a separate count for the subset that also have key2 True
    from operator import itemgetter
    KEY1 = 0
    KEY2 = 1
    getentries = itemgetter("key1", "key2")
    entries = map(getentries, list)
    key1 = len([x for x in entries if x[KEY1]])
    key2 = len([x for x in entries if x[KEY1] and x[KEY2]])
    print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2)
    

    以上数据的输出(同上):

    我有点惊讶这些花了同样多的时间。不知道有没有更快的。我肯定我忽略了一些简单的事情。

    我考虑过的另一种方法是将数据加载到数据库中并执行SQL查询,但是数据不需要持久化,我必须分析数据传输的开销等,而且数据库可能并不总是可用的。

    我无法控制数据的原始形式。

    1 回复  |  直到 16 年前
        1
  •  12
  •   Alex Martelli    16 年前

    forloop withmap ,并添加 * 100 列表的定义(结束后) ] )为了让测量结果有点实质性,我看到,在我的慢速笔记本电脑上:

    $ py26 -mtimeit -s'import co' 'co.forloop()'
    10000 loops, best of 3: 202 usec per loop
    $ py26 -mtimeit -s'import co' 'co.withmap()'
    10 loops, best of 3: 601 usec per loop
    

    i、 例如,所谓的“更蟒蛇”的方法 map for 方法——它告诉你它实际上并不是“更像蟒蛇”;—)。

    好蟒蛇的标志是 简单 ,对我来说,它推荐了我自以为是的名字……:

    def thebest():
      entries = [d['key2'] for d in list if d['key1']]
      return len(entries), sum(entries)
    

    根据测量,在整个过程中可以节省10%到20%的时间 前回路 接近。