Alvin_Kirin
Alvin_Kirin

Reputation: 43

Why does the list not save the elements?

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())

For example:

size=8 (input array size) times=4

pos=1 (The position of num in list start by 1) num=3

{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]}

Things I want:

{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]}

Upvotes: 2

Views: 63

Answers (1)

nosklo
nosklo

Reputation: 222842

This line store[v[i]]=list() is creating a new list every time

remove it and change the next append line to:

store.setdefault(v[i], list()).append(i+1)

That will create the list only if it doesn't exist.

Alternatively use collections.defaultdict(list)

Upvotes: 1

Related Questions