简体   繁体   English

如何在python中使列表的第一个元素不变?

[英]How to make the first element of the list unchange in python?

Here is my list,这是我的清单,

a = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l'],['m','n','o','p']]

and Here is my function,这是我的功能,

def add(change,unchange):
    a = change
    b = unchange
    a[0].insert(a[0].index(a[0][2]),"high_range")
    a[0].insert(a[0].index(a[0][3]),"low_range")
    print(a)
    print(b)

When I try to execute this function,当我尝试执行此功能时,

add(a,a[0])

I'm getting this output,我得到这个输出,

[['a', 'b', 'high_range', 'low_range', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p']]
['a', 'b', 'high_range', 'low_range', 'c', 'd']

But my expected output is the following,但我的预期输出如下,

[['a', 'b', 'high_range', 'low_range', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p']]
['a', 'b', 'c', 'd']

How to make the first element of the list keep on same in the second variable ?如何使列表的第一个元素在第二个变量中保持不变? Sorry I'm newbie.对不起,我是新手。

Since a list is a mutable type, when you insert values into a this also gets reflected in b , since they are pointers to the same list.由于列表是可变类型,因此当您将值插入a这也会反映在b ,因为它们是指向同一列表的指针。 You can either print b before inserting values into the list, or make b a copy of unchange like this:您可以在将值插入列表之前打印b ,或者像这样制作b一个unchange的副本:

def add(change,unchange):
    a = change
    b = unchange[:]
    a[0].insert(2, "high_range")
    a[0].insert(3, "low_range")
    print(a)
    print(b)

Also, a[0].index(a[0][2]) is redundant, you already know that the index is 2.此外, a[0].index(a[0][2])是多余的,你已经知道索引是 2。

The main problem is in line:主要问题在于:

add(a, a[0])

as you are mutating a inside the function a[0] will change as well as they point to the same thing.因为你是变异a函数里面a[0]会发生变化,以及它们指向同一个东西。 You need to design your program accordingly.您需要相应地设计您的程序。 You can refer to this answer.你可以参考这个答案。 How to clone or copy a list? 如何克隆或复制列表?

depending upon your requirement you can do this.根据您的要求,您可以执行此操作。

  1. either suply a copy while calling a function.要么在调用函数时提供一个副本。

add(a, a[0][:]) # or add(a, a[0][:]) # 或

  1. read @alec's answer.阅读@alec 的回答。

your function is perfect but execute this:您的功能很完美,但请执行以下操作:

add(a,a[0][:])

this will make the second variable, namely a[0] , a copy, which will be left unchanged.这将使第二个变量,即a[0]成为一个副本,它将保持不变。

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

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