Skip to main content
 首页 » 编程设计

Python 列表值被更改/变异

2024年10月24日9daizhj

我在这里为项目 Euler 问题 31 运行了这个简单的代码。

不需要 Euler Q;我只想知道,为什么我的列表值会发生变化,即这是打印 [2.0,2.0,2.0,2.0,2.0] 的许多列表的列表。

coins = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0] 
 
 
perms = [] 
def check(c): 
    if sum(c) == 2: 
        print c, "lol", sum(c) 
        perms.append(c) 
    return perms 
 
c = [0] * 5 
for c[0] in coins: 
    for c[1] in coins: 
        for c[2] in coins: 
            for c[3] in coins: 
                for c[4] in coins: 
                    check(c) 
 
print perms 

由于某种原因这不起作用,输出是

[[2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0]...] 
 
perms = [] 
for c1 in coins: 
    for c2 in coins: 
        for c3 in coins: 
            for c4 in coins: 
                for c5 in coins: 
                    if c1+c2+c3+c4+c5 == 2: 
                        print c1,c2,c3,c4,c5 
                        perms.append([c1,c2,c3,c4,c5]) 
 
 
print perms 

然而,这个有效,输出是

[[0.1, 0.2, 0.2, 0.5, 1.0], [0.1, 0.2, 0.2, 1.0, 0.5], [0.1, 0.2, 0.5, 0.2, 1.0],[0.1, 0.2, 0.5, 1.0, 0.2], [0.1, 0.2, 1.0, 0.2, 0.5], [0.1, 0.2, 1.0, 0.5, 0.2],[0.1, 0.5, 0.2, 0.2, 1.0], [0.1, 0.5, 0.2, 1.0, 0.2]...] 

两者有什么区别?

还有,我怎样才能缩短我的代码,也许是一个递归函数? 因此,我不是用硬币做 c1,用硬币做 c2 等等,我只用一两个循环来做同样的工作。

请您参考如下方法:

问题是 c 在被添加到 perms 之后 仍然被修改。您可以改为将副本传递给 check,这样它似乎就可以工作了。

c = [0] * 5 
for c[0] in coins: 
    for c[1] in coins: 
        for c[2] in coins: 
            for c[3] in coins: 
                for c[4] in coins: 
                    check(c[:]) # c[:] creates a copy of c 

顺便说一句,我什至不知道 for c[1] in coins 是有效的 Python 语法...

此外,您可能想看看 itertools,尤其是 product , permutations , combinations和 combinations_with_replacement .


递归函数大致如下所示:

def comb(current, target): 
    if sum(current) == target: 
        yield current 
    elif sum(current) < target: 
        for coin in coins: 
            for solution in comb(current + [coin], target): 
                yield solution 

但是,这对于获取所有硬币组合来说似乎也太慢了。