我想遍历python中的2D列表并使元素相似。我想使用索引0的ID更新我的数据库(mySQL),使其类似于索引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
如何避免这种情况发生?我可以编写一次更新所有内容的mySQL中的查询吗?如果有,我不知道会有多少个数组。我正在使用python,django和mysql。请帮忙,谢谢!
最佳答案
如果我对您的理解正确,我想先清除输入数据,我们可以删除将重新更新的list元素(对于您的情况是[3,1]
和[5,2]
),然后清除后的输入将是,使用此输入,将不会对相同的ID进行覆盖:
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]]
[[1, 3], [2, 5], [4, 5]]
将是list_two
,然后进行更新。关于python - 在Python中遍历列表时如何避免覆盖SQL UPDATE语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46333838/