【问题标题】:Dictionary does not update specific values and instead returns the same value in all the spots字典不会更新特定值,而是在所有位置返回相同的值
【发布时间】:2019-04-05 18:38:21
【问题描述】:

我正在创建一个冒泡排序算法,它接受一个列表并返回 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])

【问题讨论】:

标签: python arrays dictionary


【解决方案1】:

假设缩进与您在实际文件中的内容相匹配,您将在内部循环完成第一次运行后返回结果。尝试去凹痕。此外,将.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])

还值得一提的是,您可能不希望将日志记录功能用于任何生产运行。我认为这是一项学术活动。在较小的列表上,这不是问题,但如果您对较大的列表进行排序,您可能会遇到内存问题。

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多