Python列表值被覆盖

时间:2020-05-07 05:05:24

标签: python python-3.x list

我有一个场景,其中python实用程序将从数据库中查询案例ID的案例ID依赖关系。假设案例ID 123依赖于案例ID 234和456。

有两个列表。 r2将保留空值或1个或多个值(取决于案例ID)。每种情况下的ID依次具有v1,v2等版本,这些版本将附加到列表r3中。仅当案例ID的所有版本均已部署时,才会部署补丁123。

r2 = [187045, 187046] 
r3 = []

我从数据库日志表中获取这些版本值。一切正常,除了一个小错误导致了问题。 r3 []被新值覆盖。

for item in r2:
        cursor.execute('select distinct Version_Num from dbo.test where CMS_ID = ? and deployment_status = 0', item)
        row3 = cursor.fetchall()  #fetches a tuple
        thi_tuple = [c_tup[0] for c_tup in row3]  #converts tuple to a list
        r3 = list(map(int, thi_tuple)) #converts list to list of ints
        print(r3) 

输出如下

[2, 3] #versions of 187045
[1] #version of 187046

r3的最终输出仅为[1]。如何获得r3 = [2, 3 ,1]

我知道for循环正在使用迭代覆盖列表。

致谢

2 个答案:

答案 0 :(得分:1)

您在哪里

for item in r2:
    cursor.execute('select distinct Version_Num from dbo.test where CMS_ID = ? and deployment_status = 0', item)
    row3 = cursor.fetchall()  #fetches a tuple
    thi_tuple = [c_tup[0] for c_tup in row3]  #converts tuple to a list
    r3 = list(map(int, thi_tuple)) #converts list to list of ints
    print(r3)

替换为

for item in r2:
    cursor.execute('select distinct Version_Num from dbo.test where CMS_ID = ? and deployment_status = 0', item)
    row3 = cursor.fetchall()  #fetches a tuple
    thi_tuple = [c_tup[0] for c_tup in row3]  #converts tuple to a list
    r3 += list(map(int, thi_tuple)) # append new values
    print(r3) 

答案 1 :(得分:0)

尝试一下。我认为它将解决您的问题。 装有

r3 = list(map(int, thi_tuple)) 

使用

r3 = r3 + list(map(int, thi_tuple)) 

您的循环现在看起来像这样:

for item in r2:
    cursor.execute('select distinct Version_Num from dbo.test where CMS_ID = ? and deployment_status = 0', item)
    row3 = cursor.fetchall()  # fetches a tuple
    thi_tuple = [c_tup[0] for c_tup in row3]  # converts tuple to a list
    r3 = r3 + list(map(int, thi_tuple))  # converts list to list of ints
    print(r3)