字典不更新特定值,而是在所有位置返回相同的值

时间:2019-04-05 18:38:22

标签: python arrays dictionary

我正在创建一个冒泡排序算法,该算法接受一个列表并返回2个值:         第一个返回值:每次完成冒泡排序之后,具有列表状态的字典         第二个返回值:排序列表

    log = {}

    for n in range(len(numList)):
        for i in range(0, len(numList)-n-1):
            # Comparing numbers and swapping them
            if numList[i] > numList[i+1]:
                numList[i], numList[i+1] = numList[i+1], numList[i]
            # Creating log of the state of each pass
            log[n+1] = numList
        # Returning Results
        return log, numList

样本输入:>>> bubbleSort([9,3,5,4,1,67,78])

示例输出:({1: [3, 5, 4, 1, 9, 67, 78], 2: [3, 4, 1, 5, 9, 67, 78], 3: [3, 1, 4, 5, 9, 67, 78], 4: [1, 3, 4, 5, 9, 67, 78], 5: [1, 3, 4, 5, 9, 67, 78]}, [1, 3, 4, 5, 9, 67, 78])

1 个答案:

答案 0 :(得分:0)

假定缩进与您实际文件中的缩进匹配,则在内循环完成第一次运行后,您将返回结果。尝试消除它的凹痕。另外,将.copy()方法添加到列表中。您必须使用.copy()方法来捕获状态。否则,您将拥有一个元素列表,所有元素都指向不断更新的同一元素。

def foo(numList):

    log = {}

    for n in range(len(numList)):
        for i in range(0, len(numList)-n-1):
            # Comparing numbers and swapping them
            if numList[i] > numList[i+1]:
                numList[i], numList[i+1] = numList[i+1], numList[i]
            # Creating log of the state of each pass
            log[n+1] = numList.copy() # add the .copy()
    # Returning Results
    return log, numList # ensure proper indentation

print(foo([4, 0, 2, 3, 1]))

输出

({  1: [0, 2, 3, 1, 4], 
    2: [0, 2, 1, 3, 4], 
    3: [0, 1, 2, 3, 4], # a lot of stuff happened to get here
    4: [0, 1, 2, 3, 4]  # list was already in order, so this is repeated
    }, 
    [0, 1, 2, 3, 4])

如果您要调试/验证排序是否正常,我建议使用列表并附加数组状态的副本。这些步骤得以保留,因为列表是有序的,而字典没有排序。

此外,请注意缩进以及要在何处捕获数据。只要有更改,将日志放在if语句中就可以更改。作为第二个循环的子级,即使没有发生更改,您也将具有条目,然后顶层循环将无法捕获所有更改。

def foo(numList):

    log = [] # Change to list for a list of lists

    for n in range(len(numList)):
        for i in range(0, len(numList)-1-n):
            if numList[i] > numList[i+1]:
                numList[i], numList[i+1] = numList[i+1], numList[i]

                log.append(numList.copy()) # Append a copy

    return log, numList

print(foo([4, 0, 2, 3, 1]))

输出:

([[0, 4, 2, 3, 1], 
  [0, 2, 4, 3, 1], 
  [0, 2, 3, 4, 1], 
  [0, 2, 3, 1, 4],
  [0, 2, 1, 3, 4],
  [0, 1, 2, 3, 4]], 

 [0, 1, 2, 3, 4])

值得一提的是,您可能不希望其中的任何生产运行都具有日志记录功能。我认为这是一项学术练习。在较小的列表上,这不是问题,但是如果对大型列表进行排序,则可能会遇到内存问题。