samedi 11 juillet 2020

Attribute can only be updated once in a nested for loop

I am new to Python and have some problem with my first Python script. I have a list of data with a .tag attribute which is initially set to 0.

lst = [a, b, c, d, e, f]
for x in lst:
    x.tag = 0

Then I obtained the results for the real tags and the corresponding element indices of the list. It is stored in a list of dictionaries. Clearly, some of the elements in the list have multiple tags. Now I want to update the tags for all elements in the list, so that each element has tag attribute something like f.tag = [2,3,4,5]. I wrote the following script. The idea is to loop through each dictionary and get the indices and the tag. Then loop through each index and check if the corresponding element of the list has the tag = 0. If yes, change 0 to the new tag as a single element list; if not, that means it has been updated before, so just append the new tag. My script is below:

results = [{'indices':(2), 'tag':0}, {'indices':(1,3), 'tag':1}, {'indices':(0,3,4,5), 'tag':2}, {'indices':(4,5), 'tag':3}, {'indices':(1,5), 'tag':4}, {'5':, 'tag':5}]

for dct in results:
    indices = dct['indices']
    t = dct['tag']
    for i in indices:
        if lst[i].tag == 0:
            lst[i].tag = [t]
        elif t not in lst[i].tag:
            print('The code ever goes here')
            lst[i].tag.append(t) 

However, after I run this, I never see 'The code ever goes here' being printed out. Then I check the list, I only see all the elements with non-zero real tag being updated, but only once. This means that the tag of the elements cannot be updated a second time. This is definitely not okay since there are elements that have multiple tags and needs to be constantly updated. I have no idea what could possibly went wrong in my code.

Aucun commentaire:

Enregistrer un commentaire