如何迭代比较两个python列表的成员元素的值

How to compare iteratively the value of member elements of two python lists

我有一个不断更新的(价值方面的)python 列表,名为 up_list

每个元素的索引代表现实生活中的一个对象,如苹果、橘子、香蕉、番茄、柠檬。我想通过与列表中每个元素(Apple 或 Oranges 或 Banana 或 Tomato 或 Lemon)的比较来检查其先前版本的值。然后,如果两个列表之间的差异是 1,我想根据比较结果触发一个动作。

在编辑中插入:" 代码的objective是当列表的某个元素更新时执行一些动作。例如:如果 up_list = [0,0,0,0,0] 是初始值,并且在一次迭代后 up_list = [1,0,0,0,0],那么 Apple 的值正在更新,我可以调用一些操作将新值写入我的数据库。 "

我正在尝试这样做。

up_list = [0,0,0,0,0]

loop starts here:

  up_list_new[index] = copy.copy(up_list[index])
        up_list[index] = up_list[index] + 1

    if up_list[0]-up_list_new[0] == 1
       cursor.execute("INSERT INTO test (some data))

    elif up_list[1] - up_list_new[1] == 1
       cursor.execute(INSERT INTO test(some data))
   
    elif up_list[2]-up_list_new[2] == 1
       cursor.execute("INSERT INTO test (some data))

    elif up_list[4] - up_list_new[4] == 1
       cursor.execute(INSERT INTO test(some data))

我的问题:

  1. 我只获得了几个列表元素的值更新。我是否假设在循环的每次迭代中更新 up_list(因为 up_list[index] = up_list[index] + 1)以便我将其复制到 up_list_new 是在更新之前保留以前的版本?

  2. 有更好的方法吗?想象一下在每次成功 ifs.

    之后要采取的复杂行动

谢谢!我希望你们清楚我的问题。

编辑 2:- 这是项目中的代码。

up_list = [0, 0, 0, 0, 0] up_list1 = [0, 0, 0, 0, 0]

 valuesup1 = (location, viddate, coordinates, id, 'car','up',elapsedtime2)
    valuesup2 = (location, viddate, coordinates, id, 'motorbike', 'up', elapsedtime2)
    valuesup3 = (location, viddate, coordinates, id, 'bus', 'up', elapsedtime2)
    valuesup4 = (location, viddate, coordinates, id, 'truck', 'up', elapsedtime2)
    valuesup5 = (location, viddate, coordinates, id, 'person', 'up', elapsedtime2)
    
       
    # Find the current position of the vehicle
    if (iy > up_line_position) and (iy < middle_line_position):

        if id not in temp_up_list:
            temp_up_list.append(id)
            #print('This is UP: ', up_list)

    elif iy < down_line_position and iy > middle_line_position:
        if id not in temp_down_list:
            temp_down_list.append(id)


    elif iy < up_line_position :
        if id in temp_down_list:
            temp_down_list.remove(id)

            up_list1[index] = copy.copy(up_list[index])
            up_list[index] = up_list[index] + 1


            if up_list[0]-up_list1[0] == 1:
                #print('This is car - up: ')
                cursor.execute("INSERT INTO test (vidname,vidstart,coordinate,id,object,direction,elapsedtime) VALUES(%s,%s,%s,%s,%s,%s,%s)", (valuesup1))
         
            elif up_list[1] - up_list1[1] == 1:
                #print('This is motorbike - up: ')
                cursor.execute("INSERT INTO test (vidname,vidstart,coordinate,id,object,direction,elapsedtime) VALUES(%s,%s,%s,%s,%s,%s,%s)", (valuesup2))
                #conn.commit()
            elif up_list[2] - up_list1[2] == 1:
                #print('This is bus - up: ')
                cursor.execute("INSERT INTO test (vidname,vidstart,coordinate,id,object,direction,elapsedtime) VALUES(%s,%s,%s,%s,%s,%s,%s)", (valuesup3))
                #conn.commit()
            elif up_list[3] - up_list1[3] == 1:
                #print('This is truck - up: ')
                cursor.execute("INSERT INTO test (vidname,vidstart,coordinate,id,object,direction,elapsedtime) VALUES(%s,%s,%s,%s,%s,%s,%s)", (valuesup4))
                #conn.commit()
            elif up_list[4] - up_list1[4] == 1:
                #print('This is person - up: ')
                cursor.execute("INSERT INTO test (vidname,vidstart,coordinate,id,object,direction,elapsedtime) VALUES(%s,%s,%s,%s,%s,%s,%s)",(valuesup5))

            conn.commit()

在迭代时修改值 is generally considered bad practice。我认为解决您问题的最简单方法是复制原始列表,然后您可以对其进行迭代,例如:

up_list = [0, 0, 0, 0, 0]

# You can use [:] to create a copy of the list
up_list_new = up_list[:]

if up_list_new[0] - up_list[0] == 1:
    # Case for car
    cursor.execute(...)
         
elif up_list_new[1] - up_list[1] == 1:
    # Case for motorbike
    cursor.execute(...)

# Etc...

我认为您应该重构您的代码以提高可重用性。该项目将非常适合 OOP,因为看起来您可以按照这些行创建一个 Entry 对象:

class Entry:
    def __init__(self, location, viddate, ...):
        self.location = location
        self.viddate = viddate        
        # Etc.

    def save_to_db(self, table_name):
         cursor.execute(
             f"INSERT INTO {table_name} (vidname,vidstart,coordinate,id,object,direction,elapsedtime) "
             + f"VALUES({self.vidname},{self.vidstart},{...},{...},{...},{...},{...}"
          )
          # Etc.

这会让你省去很多重复的代码,让你的项目更加灵活。

你的问题不是很清楚 uplist 如何更新 - 但假设你有它的两个版本 -

uplist = [0, 0, 0, 0, 0]
uplist_new = [1, 0, 0, 0, 0]

# How to check if there is any change of 1 unit
any((new - old == 1) for new, old in zip(uplist_new, uplist))
# True

# How to check if there any change 
any((new != old) for new, old in zip(uplist_new, uplist))

# How to check if there is exactly one change of 1 unit
sum(new - old for new, old in zip(uplist_new, uplist)) == 1

# How to check if there is exactly one change (any number of units)
sum(((new != old) for new, old in zip(uplist_new, uplist))) == 1

要确定哪些元素已更改 - 您可以使用 enumerate 另一种理解方式

uplist = [0, 0, 0, 0, 0]
uplist_new = [1, 0, 0, 0, 0]

# How to check if there is any change of 1 unit
any((new - old == 1) for new, old in zip(uplist_new, uplist))

# How to check which indices changed
[idx for idx, truth in enumerate((new - old == 1) for new, old in zip(uplist_new, uplist)) if truth]
# [0]