【发布时间】:2018-04-13 11:46:30
【问题描述】:
我有一段代码需要几个小时才能在长列表上运行:
for elt in listCombinaisons_survivor:
effects = []
for idBadge in elt:
effects.append(dictBadges[idBadge]["Effect"])
cpt = Counter(effects)
for type_effect in cpt.keys():
cpt_effect = cpt[type_effect]
if cpt_effect > 3:
listCombinaisons_survivor.remove(elt)
break
我的listCombinaisons_survivor 包含 57 种可能性中 6 种徽章的所有可能组合 ([1,2,3,5,6,7],[1,2,3,5,6,8]...)。
对于每个可能的组合,我在字典中选择与徽章 ID 匹配的“效果”(徽章 ID 1 = 伤害),并在“效果”列表中收集所有效果。
然后我计算每个效果的出现次数,如果组合中具有相同效果的徽章超过 3 个,我会删除该组合。
有什么办法可以优化这段代码以使其更快?
我也试过了,但这不是更快:
newlist_combinations = []
for elt in listCombinaisons_survivor:
effects = []
for idBadge in elt:
effects.append(dictBadges[idBadge]["Effect"])
cpt = Counter(effects)
for type_effect in cpt.keys():
cpt_effect = cpt[type_effect]
if cpt_effect > 3:
break
if not cpt_effect > 3:
newlist_combinations.append(elt)
我不想知道需要多少时间,而是如何优化这段代码。
完整的代码可以在这里找到:
https://github.com/yirkkiller/Python/blob/master/badgesRepartition-NEW.py
谢谢!
【问题讨论】:
-
那不是一本有效的字典......
-
^^ 那也不是一本有效的字典
-
请发帖minimal reproducible example。请注意,57 选择 6 = 36288252,因此如果您对每个此类组合执行的操作花费的时间超过几分之一毫秒,则您的代码可能需要数小时才能运行。
标签: python optimization combinations