【问题标题】:List values accidentally replaced inside function列表值在函数内部意外替换
【发布时间】:2018-02-04 12:01:22
【问题描述】:

我有一个列表列表 (tableData),我想返回一个新列表 (cloneTable),它输出原始列表中每个字符串的长度,以便我可以使用函数最长字符串找到最长的字符串。我还想保留原始列表中的值。问题是我的函数运行后,原来的 List 已经转换为长度了。

我确信代码可以更好(我还在学习),但我也想了解为什么会出现这个问题。我没有分配 tableData 我将 tableData 中的值传递给 cloneTable。谢谢您的帮助!

#A list of lists
tableData = [
    ['apples','oranges','cherries','banana'], #6,7,8,6
    ['Alice','Bob','Carol','David'], #5,3,5,5
    ['dogs','cats','moose','goose'], #4,4,5,5
    ['car','train','helicopter','plane'] #3,5,10,5
]

#longestString function finds the longest string in each list of list
def longestString(table):
    cloneTable = []
    output = []

    for v1 in range(len(table)):
        cloneTable = cloneTable + [table[v1]]

    for v1 in range(len(cloneTable)):
        for v2 in range(len(cloneTable)):
            cloneTable[v1][v2] = len(cloneTable[v1][v2])

        cloneTable[v1].sort()

    for v1 in range(len(cloneTable)):
        output = output + [cloneTable[v1][-1]]

    return output

##################################################################

for v1 in range(len(tableData)): #returns the list - OK
    print(tableData[v1])

print(longestString(tableData)) #returns the longest strings - OK

for v1 in range(len(tableData)): #returns a list of string lengths - Not OK
    print(tableData[v1])

【问题讨论】:

  • 更高级的解决方案可能类似于[max(l, key=len) for l in tableData] 这利用了max 函数和一个名为list comprehension 的概念

标签: python list assign


【解决方案1】:

如果只是您正在做的参考副本/作业,不知道为什么将您的列表称为cloneTable

如果你真的想克隆它,你应该对你的列表执行一个深拷贝。跨 python 解决方案涉及使用copy.deepcopy

import copy
def longestString(table):
    cloneTable = []
    output = []

    cloneTable = copy.deepcopy(table)
    ...

【讨论】:

  • @Soviut 不正确,我们正在处理嵌套列表。
  • 啊,你是对的,由于缩进,我错过了。我将在问题中澄清这一点。
  • @user8521366 没问题。既然它有帮助,请考虑marking my answer accepted。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多