Python索引usag

2024-09-29 23:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一些代码: #问题9:深度反转 #定义一个过程,deep_reverse,它将一个列表作为输入, #并返回一个新列表,该列表与输入列表的深度相反。
#这意味着它会反转列表中的所有元素,如果有的话 #其中的元素是列表本身,反转所有元素 #在内部列表中,一直向下。在

# Note: The procedure must not change the input list.

# The procedure is_list below is from Homework 6. It returns True if 
# p is a list and False if it is not.

def is_list(p):
    return isinstance(p, list)

#For example,
def deep_reverse(n):
    n.reverse()
    for entry in n:
        if is_list(entry):
            entry.reverse() 
            deep_reverseA(entry)        
    return n

def deep_reverseA(n):
    for entry in n:
        if is_list(entry):
            entry.reverse() 
            deep_reverseA(entry)          
    return n

p = [1, [2, 3, [4, [5, 6]]]]
print deep_reverse(p)
#>>> [[[[6, 5], 4], 3, 2], 1]
print p
#>>> [1, [2, 3, [4, [5, 6]]]]

q =  [1, [2,3], 4, [5,6]]
print deep_reverse(q)
#>>> [ [6,5], 4, [3, 2], 1]
print q
#>>> [1, [2,3], 4, [5,6]]

我的问题是一旦我运行代码,p和q的值就会改变。我怎么能让它们不改变呢。我知道在python中索引是连接的,所以如果indexA=indexB,而你改变了indexA,那么indexB就会改变。这就是我在解决这个问题时遇到的问题。在


Tags: the代码元素列表returnifisdef
1条回答
网友
1楼 · 发布于 2024-09-29 23:20:10

我现在就告诉你答案,现在,再加上一个解释。在

在python中,变量只是指向存储对象的指针。正如你在帖子中所说,如果你声明foo = bar,那么foo不仅等于bar,而且{}bar。除非您明确地这样说(例如,您设置bar = 2),否则这不会改变。所以你需要一种方法来复制原始列表。在

python中有一个叫做列表切片的东西,你一定听说过。基本上,您可以使用my_list[indexA:indexB]indexA到{}的一部分。在

但你也可以把这些空格留空。indexA如果未指定,则默认为0indexB默认为-1(列表的最后一个元素)。在

因此my_list[2:]返回从my_list[2]到{}的所有元素。同样,my_list[:3]my_list[0]返回到my_list[3]。在

因此,调用my_list[:]将返回my_list的一个精确副本,而不是实际的列表本身。这就是你需要做的。在

所以把它应用到你的代码中:

def deep_reverse(n):
    ncopy = n[:]  #this is the part you need
    #rest of function, replace `n` with `ncopy`
    return ncopy

另外,不要将此应用于deep_reverseA,因为在该函数中,您正在更改复制的列表中的原始列表。您没有更改输入到deep_reverse中的列表。如果您确实将此应用于deep_reverseA,那么列表实际上不会更改(您将返回一个副本的相反值,而不是原始副本)

相关问题 更多 >

    热门问题