我有一些远远比实际应该慢的Python代码。使用列表而不是Python中的字典进行优化
#Generate planets
for t in range(stars*3): #There are 3 planets for every star, but not every star will have 3 planets
theplanet=Planet()
if random.randint(0,100) <= 25: #25% of planets have life
theplanet.tl=random.randint(1,9) #With a random tech level
else:
theplanet.tl=0 #The rest don't
theplanet.star=stardict[random.choice(list(stardict.keys()))] #Choose a random star
theplanet.star.planets+=(theplanet,) #Append the new planet to the star's list of planets
theplanet.name=theplanet.star.name+"-"+str(len(theplanet.star.planets)) #Name the planet Starname-X, where X is the length of the star's planets tuple. Since this increases every time a planet is added, it will be 1 for the first planet, 2 for the next, etc...
if math.floor((t/(stars*3))*100)==(t/(stars*3))*100: print("Generating planets: "+str((t/(stars*3))*100)+"% done.")
我很确定这个瓶颈在star=stardict[random.choice(list(
etc ...行中。我在这里猜测,但我认为字典是通过搜索字典中的每个条目并查看哪一个条目具有正确的关键字来工作的。我再次假设,列表只读取源自条目号的内存位置的信息,而对于非常大的(准确地说200,000条)列表/字典要快得多。
将dict的条目转换为列表会使此代码更快吗?我将如何做到这一点(我认为我看到了它的功能,现在审查文档...)?有没有其他方法可以让人更快地做到这一点?
您对字典查找的理解似乎不正确。字典是散列表 - 所以查找需要(平均)O(1)操作 - 不需要搜索。 – mgilson 2013-03-04 17:31:55
你认为是错的。字典是基于哈希表的,这些哈希表就是查找事物的最有效方式。 – 2013-03-04 17:32:04
@MarkRansom:虽然OP对字典查找有误解,但将其放在列表中会在技术上将其增加得更多。 (它将摆脱散列步骤和任何碰撞的可能性)。不过,这种改善可能会很微弱。 – 2013-03-04 17:49:05