我尝试了三种不同的方法于此,如由@Cyber,@jme和@mdadm以下建议:(1)面向对象的使用collections.defaultdict和(2 )正规字典,(3)嵌套字典。计时结果几乎相同。我无法回答内存使用情况和其他CPU测量结果。由于可读性和面向对象的特性,我将与#1一起进行。
以下是结果,以秒为单位。每个“尝试”迭代该代码1M次。有20个随机生成的咖啡名称,每个咖啡得到10个口味和10种颜色:
Try| Approach 1 | App 2 | App 3 |
+--+------------+-------|-------|
| 1| 41.1 | 42.1 | 42.1 |
| 2| 39.1 | 41.2 | 41.6 |
| 3| 38.6 | 41.1 | 40.1 |
| 4| 40.9 | 42.5 | 41.3 |
| 5| 39.5 | 40.1 | 39.7 |
代码如下。
方法1:
import collections, random, time
class Coffee():
def __init__(self):
self.name = name
self.color = set([])
self.taste = set([])
def __repr__(self):
return '{0} {1} {2}'.format(self.name, self.color, self.taste)
startTime = time.clock()
coffees = collections.defaultdict(Coffee)
for counter in range(1000000):
name = "Name_" + str(random.randint(1, 20))
taste = "taste_" + str(random.randint(1, 10))
color = "color_" + str(random.randint(1, 10))
coffees[name].name = name
coffees[name].taste.add(taste)
coffees[name].color.add(color)
print (time.clock() - startTime)
方法2:
import random, time
class Coffee():
def __init__(self, name, color, taste):
self.name = name
self.color = set([])
self.taste = set([])
def __repr__(self):
return '{0} {1} {2}'.format(self.name, self.color, self.taste)
startTime = time.clock()
coffeeList = {}
for counter in range(1000000):
name = "Name_" + str(random.randint(1, 20))
color = "color_" + str(random.randint(1, 10))
taste = "taste_" + str(random.randint(1, 10))
if name not in coffeeList:
coffeeObj = Coffee(name, color, taste)
coffeeList[name] = coffeeObj
else:
coffeeList[name].color.add(color)
coffeeList[name].taste.add(taste)
print (time.clock() - startTime)
方法3:
import random, time
coffeeNestedDict = {}
startTime = time.clock()
for counter in range(1000000):
name = "Name_" + str(random.randint(1, 20))
color = "color_" + str(random.randint(1, 10))
taste = "taste_" + str(random.randint(1, 10))
if name not in coffeeNestedDict:
coffeeNestedDict[name] = {"Color" : set([color]), "Taste" : set([taste])}
else:
coffeeNestedDict[name]["Color"].add(color)
coffeeNestedDict[name]["Taste"].add(taste)
print (time.clock() - startTime)
'咖啡= {名称:{颜色:[] ,口味:[]}嵌套的词典像这样的想法 – CoryKramer 2014-11-20 20:56:40
如上所述,嵌套的字典将很好地工作,如defaultdicts。 Python字典支持持续的平均时间查询,所以没有太多需要担心可伸缩性。 – jme 2014-11-20 21:08:26