Please correct me if I have worded this incorrectly.
I have two lists of rows from an SQL table. list_2 & list_4. The first element of the row contains the ID. I want to check if list_4 contains any of the IDs from list_2 and if it doesn't then to append the list_2 row to a new list (list_5) with these results. So if all the IDs from List_2 are already in List_4, then list_5 would be empty.
list_2:
for row in list_2:
print(row)
Output:
(150714, 'a:1:{i:0;s:13:"Crowd Chamber";}', 1230, 72108103, datetime.datetime(2022, 2, 17, 12, 46))
(150716, 'a:1:{i:0;s:14:"VocAlign Ultra";}', 1230, 72112640, datetime.datetime(2022, 2, 17, 13, 0, 9))
(150748, 'a:1:{i:0;s:13:"Crowd Chamber";}', 1230, 72112650, datetime.datetime(2022, 2, 17, 13, 3, 41))
list_4:
for row in list_4:
print(row)
Output:
(150713, 'Option 1', 1205, 72108103, datetime.datetime(2022, 2, 17, 12, 46), '')
(150715, 'Option 1', 1205, 72112640, datetime.datetime(2022, 2, 17, 13, 0, 9), '')
(150747, 'Option 1', 1205, 72112650, datetime.datetime(2022, 2, 17, 13, 3, 41), '')
(150747, 'a:1:{i:0;s:13:"Crowd Chamber";}', 1230, 72108103, datetime.datetime(2022, 2, 17, 12, 46), '')
(150747, 'a:1:{i:0;s:14:"VocAlign Ultra";}', 1230, 72112640, datetime.datetime(2022, 2, 17, 13, 0, 9), '')
(150747, 'a:1:{i:0;s:13:"Crowd Chamber";}', 1230, 72112650, datetime.datetime(2022, 2, 17, 13, 3, 41), '')
(150748, 'a:1:{i:0;s:13:"Crowd Chamber";}', 1230, 72112650, datetime.datetime(2022, 2, 17, 13, 3, 41), '')
(150716, 'a:1:{i:0;s:14:"VocAlign Ultra";}', 1230, 72112640, datetime.datetime(2022, 2, 17, 13, 0, 9), '')
(150715, 'Option 1', 1205, 72112640, datetime.datetime(2022, 2, 17, 13, 0, 9), '')
(150747, 'Option 1', 1205, 72112650, datetime.datetime(2022, 2, 17, 13, 3, 41), '')
(150713, 'Option 1', 1205, 72108103, datetime.datetime(2022, 2, 17, 12, 46), '')
(150714, 'a:1:{i:0;s:13:"Crowd Chamber";}', 1230, 72108103, datetime.datetime(2022, 2, 17, 12, 46), '')
Current code:
for x in list_2:
for y in list_4:
if x[0]==y[0]:
print("Match")
else:
print("No match")
list_5.append(x)
print(list_5)
But of course y[0]
won't match all the x[0]
loops so I'm just collecting all the rows when I want to only be collecting the updates.
CodePudding user response:
You need to wait to have iterated on the whole list_4
before deciding if you've seen it or not. Then use for/break/else
pattern : you go in the else
if no break
has been used
list_5 = []
for x in list_2:
for y in list_4:
if x[0] == y[0]:
break
else:
list_5.append(x[0])
But a more performant way would be to extract the IDs in a set
then just look into it
ids = {y[0] for y in list_4}
list_5 = []
for x in list_2:
if x[0] not in ids:
list_5.append(x[0])