首页 > 解决方案 > Python - 字符串列表列表

问题描述

所以,基本上我有一个队列(字符串列表列表)。现在,假设我想将“好的”附加到索引 1 处的列表中,为什么要为 Queue 中的所有列表附加它?如何仅在队列内将值附加到特定列表?

Queue = []
temp = []
Queue.append(temp) # 12 - 8
Queue.append(temp)
Queue.append(temp)
Queue[1].append('okay')
print(Queue)
[['okay'], ['okay'], ['okay']]

标签: pythonlistdata-structures

解决方案


Because the three items in Queue are not three different empty lists: they're all temp. Thus temp, Queue[0], Queue[1] and Queue[2] are all the same object and modifying one of them has the result of modifying them all.

Try the following code instead:

Queue = []
Queue.append([])
Queue.append([])
Queue.append([])
Queue[1].append('okay')
print(Queue)

推荐阅读