I have the following code, comparing two lists that contains equally structured tuples:
list_one = [('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aaa','bbb'), ('id_04','aab','bbc')]
list_two = [('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aad','bbd')]
for tupl in list_one:
for tup in list_two:
if tupl[0] == tup[0] and (tupl[1] != tup[1] or tupl[2] != tup[2]):
print("There is a difference on "+
"{} between the two lists".format(tup[0]))
this code would print
There is a difference on id_03 between the two lists
which is the expected result.
But I wonder if there is a better way to achieve the same result, maybe whitout iterating through list_two
for every item of list_one
, but any suggestion will be appreciated.
2 Answers 2
I think you would be better off using set
. It provides features like set difference by itself, thereby reducing a lot of work at your end:
set_one = set([('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aaa','bbb'), ('id_04','aab','bbc')])
set_two = set([('id_01','aaa','bbb'), ('id_02','aaa','bbb'), ('id_03','aad','bbd')])
for difference in (set_two - set_one):
print(f"There is a difference on {difference[0]} between the two lists")
Looks like you should use a dictionary instead of a list. The id_01
in your case would be the key for each dictionary and the other items can be contained in a list.
Like this (same for dict_two)
dict_one = {
'id_01': ['aaa', 'bbb'],
'id_02': ['aaa', 'bbb'],
}
then you can iterate over the keys
for k in dict_one.keys():
if dict_one[k][0] != dict_two[k][0] or dict_one[k][1] != dict_two[k][1]:
print("there is a diff....")
-
\$\begingroup\$ This doesn't work the same as the OP's \$\endgroup\$2020年09月29日 14:02:10 +00:00Commented Sep 29, 2020 at 14:02
-
1\$\begingroup\$ It does what was asked for
a better way to achieve the same result, maybe whitout iterating through list_two for every item of list_one,
. What do you think is missing in my suggestion? The data structure used by OP seems inappropriate for what they want to do with it, don't you agree? \$\endgroup\$user985366– user9853662020年09月29日 16:24:06 +00:00Commented Sep 29, 2020 at 16:24 -
1\$\begingroup\$ it'd raise an error for key id_04 \$\endgroup\$hjpotter92– hjpotter922020年09月29日 23:18:44 +00:00Commented Sep 29, 2020 at 23:18
-
\$\begingroup\$ @hjpotter92 correct. I assumed too much \$\endgroup\$user985366– user9853662020年09月29日 23:50:24 +00:00Commented Sep 29, 2020 at 23:50
id_03
were the same in both lists what output would you expect? \$\endgroup\$