Reputation: 243
I would like to iterate through my 2D list in python and make the elements similar. I want to update my database (mySQL) with IDs of index 0 to be like index 1.
list_one = [ [1,3], [2,5], [3,1], [4,5], [5,2] ]
loop 1: UPDATE 1 with 3
>> list_one[0] == 3
loop 2: UPDATE 2 with 5
>> list_one[1] == 5
loop 3: UPDATE 3 with 1
>> list_one[2] == 1
## if you look closely, the first loop will be re-updated by the third loop because list_one[0] is currently == 3.
## So loop 1 will also output as 1 along with loop 3. list_one[0] is overwritten.
>> list_one[0] == 1
How can I avoid this from happening? Is there a query in mySQL I can write to update everything at once? If there is, I don't know how many arrays I will have. I am using python, django and mysql. Please help, thank you!
Upvotes: 0
Views: 133
Reputation: 6556
If I understood you correctly, I would like to clean the input data first, we can remove the list element which will be re-updated,for your case is [3,1]
and [5,2]
, after that the cleaned input will be [[1, 3], [2, 5], [4, 5]]
, with this input, the overwrite will not happen for same IDs:
list_one = [ [1,3], [2,5], [3,1], [4,5], [5,2] ]
list_two = []
for i in list_one:
if i[0] not in [el[1] for el in list_two]:
list_two.append(i)
print(list_two) #here list_two will be [[1, 3], [2, 5], [4, 5]]
list_two
will be [[1, 3], [2, 5], [4, 5]]
, then do your update.
Upvotes: 1