Skip to main content
 首页 » 编程设计

python之在 Python 中使用列表而不是字典进行优化

2025年05月04日16itcoder

我有一些 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... dict 中的每个条目并查看哪个条目具有正确的键。列表,我再次假设,只会在从条目号派生的内存位置读取信息,对于非常大的(准确地说是 200,000 个条目)列表/听写要快得多。

将字典的条目转换为列表会使这段代码更快吗?我该怎么做(我以为我看到了它的功能,现在正在查看文档......)?有没有其他任何人注意到可以加快速度的方法?

请您参考如下方法:

您每次通过循环都在创建一个列表,但该列表是不变的。将其移出循环。

starlist=list(stardict.keys()) 
... 
    theplanet.star=stardict[random.choice(starlist)]     #Choose a random star 

问题几乎可以肯定不在 dict 查找中。它们基于非常快的哈希表。