Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the missing element to second list by comparing two lists

Tags:

python

I have two lists which contain datewise data and want to add a missing data of a date in list2 by comparing with list1

Lists like below

 list1=['2019-06-01', '2019-06-02', '2019-06-03', '2019-06-04', '2019-06-05']
 list2=[['2019-06-01','3'], ['2019-06-02','0'],['2019-06-04','1'], ['2019-06-05', '4']]

Here in list2 doesn't contain data for 2019-06-03, so want to add that missing data of that date to list2 with empty values and final values of list2 contain like below

list2=[['2019-06-01','3'], ['2019-06-02','0'],['2019-06-03','']['2019-06-04','1'], ['2019-06-05', '4']]

Below is the code I'm trying with to get missing values to another list

 for a, b in itertools.izip_longest(list1,list2):
     if a!=b[0]:
         print a

which prints like below

  2019-06-03
  2019-06-04
  2019-06-05

Can somebody guide me here

like image 849
Chethu Avatar asked Nov 28 '22 19:11

Chethu


1 Answers

This is one approach using itertools.chain and set

Ex:

from itertools import chain

list1=['2019-06-01', '2019-06-02', '2019-06-03', '2019-06-04', '2019-06-05']
list2=[['2019-06-01','3'], ['2019-06-02','0'],['2019-06-04','1'], ['2019-06-05', '4']]

check_val = set(chain.from_iterable(list2))

for i in list1:
    if i not in check_val:
        list2.append([i, ""])
print(list2)
print(sorted(list2, key=lambda x: x[0]))

Output:

[['2019-06-01', '3'], ['2019-06-02', '0'], ['2019-06-04', '1'], ['2019-06-05', '4'], ['2019-06-03', '']]
[['2019-06-01', '3'], ['2019-06-02', '0'], ['2019-06-03', ''], ['2019-06-04', '1'], ['2019-06-05', '4']]
like image 184
Rakesh Avatar answered Dec 05 '22 16:12

Rakesh