我嘗試了三種不同的方法於此,如由@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