简体   繁体   中英

comparing list values in python

I have a list defined as list1 la where I have some values and list2 lb which also has some values, now I would like to match the values in both list and if list2 contains any of the match in list1 then create a matched list and along with this another list where I will map another list gh or mn value based on the conditions, once this is done it should create a final list with only values in list1. What I have tried so far doesn't provides the desired output.

lb=[1,2,3,4,5,6]
la = [1,2,3,4,8]
cd=[]
ef=[]
gh=[]
ij=[]
mn=[]       

for keya in la: #main list
    ef.append('0') #main val
    if (x in la for x in lb):
        cd=(la and lb)
        gh.append('1')
d1 = [{'Tpj_id': a, 'status': t} for a, t in zip(cd, gh)] 
d2 = [{'Tpj_id': s, 'status': j} for s, j in zip(la, ef)]
if len(cd) == 0:
    #print(d2)
    d4=d2
    print(d4)
else:
    ij=[elem for elem in la if elem not in lb]
    for keyg in ij:
        mn.append('0')
    d3 = [{'Tpj_id': o, 'status': p} for o, p in zip(ij, mn)]
    d4 = d3 + d1
    print(d4)

current output :

[{"Tpj_id": 1, "status": "1"}, {"Tpj_id": 2, "status": "1"}, {"Tpj_id": 3, "status": "1"}, {"Tpj_id": 4, "status": "1"}, {"Tpj_id": 5, "status": "1"}, {"Tpj_id": 6, "status": "1"}, {"Tpj_id": 8, "status": "0"}]

desired output :

[{"Tpj_id": 1, "status": "1"}, {"Tpj_id": 2, "status": "1"}, {"Tpj_id": 3, "status": "1"}, {"Tpj_id": 4, "status": "1"}, {"Tpj_id": 8, "status": "0"}]

You can try this

lb=[1,2,3,4,5,6]
la = [1,2,3,4,8]
non_comn_list = [item for item in la if item not in lb]
com_list  = [item for item in la if item not in non_comn_list]
list = [{'Tpj_id': a, 'status': 1} for a in com_list] 
[list.append(val) for val in [{'Tpj_id': a, 'status': 0} for a in non_comn_list]]
list

Output

[{'Tpj_id': 1, 'status': 1},
 {'Tpj_id': 2, 'status': 1},
 {'Tpj_id': 3, 'status': 1},
 {'Tpj_id': 4, 'status': 1},
 {'Tpj_id': 8, 'status': 0}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM