【问题标题】:How to avoid overwriting a SQL UPDATE statement when looping through list in Python?在 Python 中循环遍历列表时如何避免覆盖 SQL UPDATE 语句?
【发布时间】:2018-03-02 05:03:02
【问题描述】:

我想在 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。请帮忙,谢谢!


【问题讨论】:

    标签: python mysql sql django python-2.7


    【解决方案1】:

    如果我理解正确,我想先清理输入数据,我们可以删除将重新更新的列表元素,你的情况是[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]],然后进行更新。

    【讨论】:

    • 啊,所以将它们分成两个列表?我还意识到,如果我从具有最低索引 [1] 的元素开始更新,它将防止覆盖任何内容。试试你的想法。非常感谢!
    • 我刚试过,两个列表都以相同的顺序返回相同的元素。
    • @Marvin,你确定你使用的是正确的代码吗? list_one[ [1,3], [2,5], [3,1], [4,5], [5,2] ],应用代码后,list_two 将是[[1, 3], [2, 5], [4, 5]]
    猜你喜欢
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2018-03-13
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多