copying lists changes the code?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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) |
当运行代码并输入所有数据时。我试着查一下清单
1 2 | >>> aaa [20.0, 1.0, 20.0, 20.0, 20.0, 20.0, 20.0] |
但当我输入test1时,就会发生这种情况。
1 2 | >>> test1 [20.0, 1.0, 20.0, 20.0, 20.0, 20.0, 20.0] |
我对名单做了什么错事吗?我可以将列表test1复制到另一个列表"在本例中为aaa",但是当我尝试从aaa中删除列表的部分时,它也会从test1中删除它!
当aaa=test1时,实际上没有两个列表。分配只是复制对列表的引用,而不是实际列表,因此aaa和test1在分配之后都引用相同的列表。
您可以这样做:
1 | aaa= list(test1) |
可能重复:如何克隆或复制列表?