在我编写的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查询,但是数据不需要持久化,我必须分析数据传输的开销等,而且数据库可能并不总是可用的。
我无法控制数据的原始形式。