2
我如何寫這個列表理解?如何使這個列表理解
for i in range(len(genes)):
if compareGenes(genes[i], target) > count:
best = genes[i]
count = compareGenes(genes[i], target)
我如何寫這個列表理解?如何使這個列表理解
for i in range(len(genes)):
if compareGenes(genes[i], target) > count:
best = genes[i]
count = compareGenes(genes[i], target)
max
帶發電機的理解將是一個不錯的方法。
count, best = max((compareGenes(k, target), k) for k in genes)
或者,可使用key
參數max
:
best = max(genes, key=lambda k: compareGenes(k, target))
哈!英雄所見略同。 –
[閱讀了](http://carlgroner.me/Python/2011/11/09/An-Introduction-to-List -Comprehensions合Python.html);這樣更有趣。 :) – Miguel
在Python for for循環迭代器,所以循環索引是一個非常糟糕的跡象 - 這意味着你做錯了什麼。 ''對於基因中的基因:''不''對於範圍內的我(len(基因)):''。 –
我喜歡@ nneonneo的答案 - 我給了同樣的符號符號解決方案。我認爲他幾秒鐘就打敗了我,所以我撤回了我。 –