Explanation of List Comprehensions

北城以北 提交于 2020-01-05 08:10:26

问题


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))

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?


回答1:


for i in [c for c in coinValueList if c <= change]:

is the same as:

coins = []
for c in coinValueList:
    if c <= change:
        coins.append(c)

for i in coins:
    #do your stuff

the list comprehension is much easier to code and better to read.
list comprehension is the "python-way".




回答2:


let me explain

[c for c in coinValueList if c <= change]

create new list with values from coinValueList which are less than change inside After this You iterate over new list.

N.B. If You insist on using comprehension there Consider generator statement It will work same way but without memory consumption.

so result for loop should be not

for i in c:
    for c in coinValueList:
        if c<= change:

but

for i in coinValueList:
    if i<= change:


来源:https://stackoverflow.com/questions/19559625/explanation-of-list-comprehensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!