【问题标题】:Optimizing a feature in Python优化 Python 中的功能
【发布时间】: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

谢谢!

【问题讨论】:

标签: python optimization combinations


【解决方案1】:

除了非常不清楚的变量名,你的算法基本上归结为:

def filter_effects(listCombinaisons_survivor):
    for elt in listCombinaisons_survivor
        cpt = Counter(dictBadges[idBadge]["Effect"] for idBadge in elt)
        if all(value <= 3 for key, value in cpt.items()):
            yield elt

PS。如果我查看您的完整脚本,我会建议您首先学习 Python 的基础知识。有很多事情可以做得更清晰、更健壮、更简单

我建议:

  • Python 旋风之旅 (link)
  • 流利的 Python (link)
  • David Baumgold 的“像专业人士一样循环”

【讨论】:

  • 感谢 Maarten :-) 我确实不是开发人员,而是 DevOps,所以没有适当的开发培训,只是自学。我知道有很多东西我还没有掌握,我只是尽量让这个脚本发挥作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多