Python 为什么列表不保存元素?
例如:Python 为什么列表不保存元素?,python,list,dictionary,Python,List,Dictionary,例如: size=8(输入数组大小)times=4 pos=1(num在列表中的位置以1开头)num=3 while(True): size,times = map(int,input().split()) v=list(map(int,input().split())) store=dict() for i in range(size): store[v[i]]=list() store[v[i]].append(i+1)
size=8
(输入数组大小)times=4
pos=1
(num在列表中的位置以1开头)num=3
while(True):
size,times = map(int,input().split())
v=list(map(int,input().split()))
store=dict()
for i in range(size):
store[v[i]]=list()
store[v[i]].append(i+1)
print(store)
while(times>0):
pos,num = map(int,input().split())
我想要的东西:
{1: [1]}
{1: [1], 3: [2]}
{1: [1], 3: [2], 2: [3]}
{1: [1], 3: [2], 2: [4]}
{1: [1], 3: [2], 2: [4], 4: [5]}
{1: [1], 3: [6], 2: [4], 4: [5]}
{1: [1], 3: [6], 2: [7], 4: [5]}
{1: [8], 3: [6], 2: [7], 4: [5]}
此行
store[v[i]]=list()
每次都在创建一个新列表
删除它并将下一个附加行更改为:
{1: [1]}
{1: [1], 3: [2]}
{1: [1], 3: [2], 2: [3]}
{1: [1], 3: [2], 2: [3,4]}
{1: [1], 3: [2], 2: [3,4], 4: [5]}
{1: [1], 3: [2,6], 2: [4], 4: [5]}
{1: [1], 3: [2,6], 2: [3,4,7], 4: [5]}
{1: [1,8], 3: [2,6], 2: [3,4,7], 4: [5]}
只有当列表不存在时,才会创建该列表
或者使用collections.defaultdict(列表)
store.setdefault(v[i], list()).append(i+1)