为了账号安全,请及时绑定邮箱和手机立即绑定

为什么输出L2、L3时,后面插入的字符串还是重复插入,明明设置不是一个队列内?

# Enter a code

L=['Alice','Bob','Candy','David','Ellena']

L1 = L

L1.append('Gen')

L2 = L


L1.append('Phoebe')

L1.append('Zero')

print(L1)


L2.append('Zero')

L2.insert(6,'Phoebe')

print(L2)

L3=['Gen','Phoebe','Zero']

print(L+L3)


正在回答

1 回答

因为两者指向同一个列表对象,如:

list = [1, 2, 3]

list1 = list
list1.append(4)
print('list1', list1)
print('list', list)

list1 [1, 2, 3, 4]
list [1, 2, 3, 4]


要避免这种情况,使用copy,如:
list2 = list.copy()
print('list2', list2)
list2.append(100)
print('list2', list2)
print('list', list)

list2 [1, 2, 3, 4]
list2 [1, 2, 3, 4, 100]
list [1, 2, 3, 4]
0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为什么输出L2、L3时,后面插入的字符串还是重复插入,明明设置不是一个队列内?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信