繁体   English   中英

Python覆盖了我的原始列表

[英]Python overwriting my original list

我正在尝试编写一段代码,在其中我知道在4个数字的组合中3个位置正确。 我想遍历所有6个可能的数字并创建所有可能的迭代。 本质上,如果我有一个组合[1,2,3,4]并且我知道3在正确的位置,我想生成:[2,2,3,4],[3,2,3,4 ],[4,2,3,4],[5,2,3,4],[6,2,3,4],[1,1,3,4-],[1,3,3,4- ],[1,4,3,4],[1,5,3,4],[1,6,3,4],[1,2,1,4],等等。

我有这段代码,生成所有可能的迭代为[6,6,6,6]

def create_guess_list(guess):
guess_list = []
for i in range(0,4):
    for j in range(1,7):
        temp = guess
        if j != temp[i]:
            temp[i] = j
            guess_list.append(temp)
return guess_list

我假设每次创建新组合时,即使我将其放入临时列表中,Python也会覆盖它。 如何避免这种情况,而不必每次都创建空白列表并随便添加? (或者这是唯一的方法吗?)

复制列表最简单的方法是使用完整切片。 更改此行

temp = guess

对此

temp = guess[:]

如果不通过切片或其他方式复制列表,则您将有两个指向同一列表的变量。

您可以使用itertools.product生成所有可能的组合,然后过滤掉不匹配的数字:

import itertools
def guess_list (guess, correct):
    for combination in itertools.product(range(1, 7), repeat=4):
        if sum(c == g for c, g in zip(combination, guess)) == correct:
            yield combination
>>> list(guess_list([1, 2, 3, 4], 3))
[(1, 1, 3, 4), (1, 2, 1, 4), (1, 2, 2, 4), (1, 2, 3, 1), (1, 2, 3, 2), (1, 2, 3, 3), (1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 3, 6), (1, 2, 4, 4), (1, 2, 5, 4), (1, 2, 6, 4), (1, 3, 3, 4), (1, 4, 3, 4), (1, 5, 3, 4), (1, 6, 3, 4), (2, 2, 3, 4), (3, 2, 3, 4), (4, 2, 3, 4), (5, 2, 3, 4), (6, 2, 3, 4)]

对于您的解决方案,问题在于您正在修改原始猜测。 temp = guess您仅将引用复制到猜测列表。 因此,变量guesstemp引用同一个列表对象。 然后,当您执行temp[i] = j ,您将更改两个变量都引用的该列表对象的项目。 因此,您正在此处更改原始猜测(使所有进一步的guess检查不正确)。 出于相同的原因,您还继续将相同的对象附加到guess_list列表中。 为了解决这个问题,您必须创建一个guess列表的副本。 您可以使用temp = guess[:]做到这一点。

temp = guess被分配的内容guess到可变称为temp (二者变量指向同一对象)。

为了创建一个独立的副本,您应该像这样从guess创建一个新列表:

temp = list(guess)  # or temp = guess[:]
from itertools import combinations, product

ALPHABET = [1, 2, 3, 4, 5, 6]
SAME = {a:[a] for a in ALPHABET}
DIFF = {a:[x for x in ALPHABET if x != a] for a in ALPHABET}

def all_possible_solutions(guess, num_right):
    # how many items need to be substituted?
    width = len(guess)
    num_wrong = width - num_right

    # which items should be substituted?
    for replace_at in combinations(range(width), num_wrong):

        # figure out new basis
        basis = [
            DIFF[g] if index in replace_at else SAME[g]
            for index,g in enumerate(guess)
        ]

        # return combinations from new basis
        for combo in product(*basis):
            yield combo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM