【发布时间】:2011-02-28 12:55:46
【问题描述】:
在我正在编写的 Python 程序中,我比较了使用 for 循环和递增变量与使用 map(itemgetter) 和 len() 计算列表中的字典条目时的列表理解。使用 each 方法需要相同的时间。我做错了什么还是有更好的方法?
这是一个大大简化和缩短的数据结构:
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'}
]
这是for循环版本:
#!/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
这是另一个可能更 Pythonic 的版本:
#!/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)
以上数据的输出(与之前相同):
Counts: key1: 3, subset key2: 2
我有点惊讶这些需要相同的时间。我想知道是否有更快的东西。我确定我忽略了一些简单的事情。
我考虑过的一种替代方法是将数据加载到数据库中并执行 SQL 查询,但数据不需要持久化,我必须分析数据传输等的开销以及数据库可能并不总是可用。
我无法控制数据的原始形式。
上面的代码不适用于样式点。
【问题讨论】:
标签: python dictionary map loops list-comprehension