问题描述
我正在尝试学习Python 3.x的动态编程和递归.下面的代码是我的教科书中的一个简单示例:
I'm attempting to learn about dynamic programming and recursion for Python 3.x. The code below is a simple example from my textbook:
def recMC(coinValueList, change):
minCoins = change
if change in coinValueList:
return 1
else:
for i in [c for c in coinValueList if c <= change]:
numCoins = 1 + recMC(coinValueList, change-i)
if numCoins < minCoins:
minCoins = numCoins
return minCoins
print(recMC([1,5,10,25], 63))
我真的很难理解这里的第6行,即对行的理解.我完全不确定这里发生了什么,以及如何将其分解为多个循环以更容易理解.这是我目前的想法:
I'm really struggling to understand line 6 here, the line comprehension. I'm completely unsure what is happening here, and how to break it down into loops to comprehend a bit easier. This is my thought as it stands:
for i in c:
for c in coinValueList:
if c<= change:
但是我不知道这是如何反复进行的.也许一个知识渊博的人可以用不同于我的书和教授的方式解释这一点?
But I don't understand how this is iterating through. Perhaps someone with better knowledge could explain this in a different way than my book and prof?
推荐答案
for i in [c for c in coinValueList if c <= change]:
与以下相同:
coins = []
for c in coinValueList:
if c <= change:
coins.append(c)
for i in coins:
#do your stuff
列表理解更容易编写代码,更易于阅读.
列表理解是"python-way".
the list comprehension is much easier to code and better to read.
list comprehension is the "python-way".
这篇关于列表理解的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!