[英]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.我有一个定义为 list1
la
的列表,其中我有一些值,而 list2 lb
也有一些值,现在我想匹配两个列表中的值,如果 list2 包含 list1 中的任何匹配项,则创建一个匹配的列表以及有了这个另一个列表,我将根据条件映射另一个列表gh
或mn
值,一旦完成,它应该创建一个仅包含 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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.