簡體   English   中英

在Python中遍歷列表時如何避免覆蓋SQL UPDATE語句?

[英]How to avoid overwriting a SQL UPDATE statement when looping through list in Python?

我想遍歷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] ,然后清除輸入將是[[1, 3], [2, 5], [4, 5]] ,使用此輸入,對於相同的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]]

list_two將是[[1, 3], [2, 5], [4, 5]] ,然后進行更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM