【问题标题】:copying lists changes the code? [duplicate]复制列表会更改代码? [复制]
【发布时间】:2018-06-07 02:34:06
【问题描述】:
cows = ["aaa","aab","aac","aad","aae","aaf","aag","aah","aai"]
h = ["aaa","aab","aac","aad","aae","aaf","aag","aah","aai"]
test1 = []
day1 = []
day2 = []
day3 = []
day4 = []
day5 = []
day6 = []
day7 = []
aaa = []
days = ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7"]
w = ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7"]
print("Here are your cows :")
print(h)
print("You will need to input the total liters the cow has milked during the day starting from cow aaa to aai.")
for x in range(7):
    print(days[0], end = " ")
    days.pop(0)
    cows = h[0:9]
    for x in range(9):
        print("Cow : ", cows[0])
        test1.append(float(input("How many liters did you milk the cow? ")))
        cows.pop(0)
aaa = test1
for x in range(8):
    aaa.pop(1)
for x in range(8):
    aaa.pop(2)
for x in range(8):
    aaa.pop(3)
for x in range(8):
    aaa.pop(4)
for x in range(8):
    aaa.pop(5)
for x in range(8):
    aaa.pop(6)
for x in range(8):
    aaa.pop(7)

当代码运行并输入所有数据时。我尝试检查列表

>>> aaa
[20.0, 1.0, 20.0, 20.0, 20.0, 20.0, 20.0]

但是当我输入 test1 时,就会发生这种情况。

>>> test1
[20.0, 1.0, 20.0, 20.0, 20.0, 20.0, 20.0]

我对列表做错了吗?我可以将列表 test1 复制到另一个列表“在这种情况下为 aaa”,但是当我尝试从 aaa 中删除部分列表时,它也会从 test1 中删除它!

【问题讨论】:

    标签: python


    【解决方案1】:

    aaa = test1 不会“复制列表”,它会将同一个列表分配给另一个变量。您现在有两个变量(aaatest1)引用同一个列表,因此您通过其中一个执行的任何操作(例如,附加元素)当然也可以从另一个。如果您想将test1 的内容复制到一个新列表 并将该列表分配给aaa,您可以使用切片:aaa = test1[:]

    【讨论】:

      【解决方案2】:

      使用 aaa = test1,您实际上没有两个列表。赋值只是复制对列表的引用,而不是实际的列表,因此 aaa 和 test1 在赋值后都引用同一个列表。

      你可以这样做:

      aaa= list(test1)
      

      可能重复:How to clone or copy a list?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-20
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多