comparing two lists
Peter Otten
__peter__ at web.de
Thu Feb 25 03:04:19 EST 2021
On 25/02/2021 01:42, Davor Levicki wrote:
> i have two lists
>
> list1 = ['01:15', 'abc', '01:15', 'def', '01:45', 'ghi' ]
> list2 = ['01:15', 'abc', '01:15', 'uvz', '01:45', 'ghi' ]
>
> and when I loop through the list
>
>
> list_difference = []
> for item in list1:
>
> if item not in list2:
> list_difference.append(item)
>
>
> and I managed to get the difference, but I need time as well
> because it is a separate item and 'uvz' does not mean to me anything in the list with a few thousand entries.
> I tried to convert it to the dictionary, but it overwrites with last key:value {'01:15' : 'def'}
The problem is underspecified, but here's my guess:
Are the even items unique? If so you can build the dicts with keys and
values swapped:
>>> list1 = ['01:15', 'abc', '01:15', 'def', '01:45', 'ghi' ]
>>> list2 = ['01:15', 'abc', '01:15', 'uvz', '01:45', 'ghi' ]
>>> d1 = dict(zip(list1[1::2], list1[::2]))
>>> d2 = dict(zip(list2[1::2], list2[::2]))
>>> d1
{'abc': '01:15', 'def': '01:15', 'ghi': '01:45'}
>>> d2
{'abc': '01:15', 'uvz': '01:15', 'ghi': '01:45'}
To calculate the difference:
>>> d1.keys() - d2
{'def'}
>>> {d1[k]: k for k in d1.keys() - d2}
{'01:15': 'def'}
More information about the Python-list
mailing list