Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么列表不保存元素?_Python_List_Dictionary - Fatal编程技术网

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)