更改列表的副本
Altering a copy of a list
我想更改列表的副本而不更改原始列表。我的代码显示副本存储在与原始文件不同的内存地址。但是原始列表随副本一起更改。我做错了什么?
original = ['Humpty', 'Dumpty'],['Jack', 'Sprat']
revised = list(original[:])
# Reverse a name on the revised list.
# Don't alter the original list.
revised[0][0],revised[0][1]=revised[0][1],revised[0][0]
print(f"\nThe original list:\t{original}\nAnd its address:\t{id(original)}")
print(f"\nThe revised list:\t{revised}\nAnd its address:\t{id(revised)}\n")
输出:
The original list: (['Dumpty', 'Humpty'], ['Jack', 'Sprat'])
And its address: 140586839997408
The revised list: [['Dumpty', 'Humpty'], ['Jack', 'Sprat']]
And its address: 140586839996848
(我是 运行 Python 3.7.4。)
您需要复制内部列表的值。
original = [['Humpty', 'Dumpty'], ['Jack', 'Sprat']]
revised = [ar[:] for ar in original]
# Reverse a name on the revised list.
# Don't alter the original list.
revised[0][0], revised[0][1] = revised[0][1], revised[0][0]
print(f"\nThe original list:\t{original}\nAnd its address:\t{id(original)}")
print(f"\nThe revised list:\t{revised}\nAnd its address:\t{id(revised)}\n")
输出:
The original list: [['Humpty', 'Dumpty'], ['Jack', 'Sprat']]
And its address: 140210727731136
The revised list: [['Dumpty', 'Humpty'], ['Jack', 'Sprat']]
And its address: 140210729012672
我想更改列表的副本而不更改原始列表。我的代码显示副本存储在与原始文件不同的内存地址。但是原始列表随副本一起更改。我做错了什么?
original = ['Humpty', 'Dumpty'],['Jack', 'Sprat']
revised = list(original[:])
# Reverse a name on the revised list.
# Don't alter the original list.
revised[0][0],revised[0][1]=revised[0][1],revised[0][0]
print(f"\nThe original list:\t{original}\nAnd its address:\t{id(original)}")
print(f"\nThe revised list:\t{revised}\nAnd its address:\t{id(revised)}\n")
输出:
The original list: (['Dumpty', 'Humpty'], ['Jack', 'Sprat'])
And its address: 140586839997408
The revised list: [['Dumpty', 'Humpty'], ['Jack', 'Sprat']]
And its address: 140586839996848
(我是 运行 Python 3.7.4。)
您需要复制内部列表的值。
original = [['Humpty', 'Dumpty'], ['Jack', 'Sprat']]
revised = [ar[:] for ar in original]
# Reverse a name on the revised list.
# Don't alter the original list.
revised[0][0], revised[0][1] = revised[0][1], revised[0][0]
print(f"\nThe original list:\t{original}\nAnd its address:\t{id(original)}")
print(f"\nThe revised list:\t{revised}\nAnd its address:\t{id(revised)}\n")
输出:
The original list: [['Humpty', 'Dumpty'], ['Jack', 'Sprat']]
And its address: 140210727731136
The revised list: [['Dumpty', 'Humpty'], ['Jack', 'Sprat']]
And its address: 140210729012672