python中基于元组索引的列表比较

python中基于元组索引的列表比较,python,list,tuples,Python,List,Tuples,我需要通过比较两个元组的具体索引值来比较它们 cu_list = [(1024, '9251', 'b'), (1024, '9254', 'b'), (1024, '9253', 'ad'), (1024, '9231', 'l'), (1024, '9252', 'ad')...] de_list = [(1024, '9251', 'ad'), (1024, '9254', 'nc'), (1024, '9253', 'l'), (1024, '9231', 'nc'), (1024, '

我需要通过比较两个元组的具体索引值来比较它们

cu_list = [(1024, '9251', 'b'), (1024, '9254', 'b'), (1024, '9253', 'ad'), (1024, '9231', 'l'), (1024, '9252', 'ad')...]
de_list = [(1024, '9251', 'ad'), (1024, '9254', 'nc'), (1024, '9253', 'l'), (1024, '9231', 'nc'), (1024, '9252', 'nc')...]
我需要比较这些列表,并形成一个包含cu_列表中所有元素的新列表,如果比较成功,则更新cu_列表中元素的值

comparison rules:
1- If the second element of tuple in cu_list is found in de_list, then comparison is successful.
2- If the value on 3rd index in tuple of de_list is 'b' then the resultant list must contain the value as 'xb' else it should be the same value as in cu_list.
3- If the value on 3rd index in tuple of de_list is 'l' then the resultant list must contain the value as 'xl' else it should be the same value as in cu_list.

Hence if we follow the comparison rules we may get the following result:
resultant_list = [(1024, '9251', 'b'), (1024, '9254', 'b'), (1024, '9253', 'xl'), (1024, '9231', 'l'), (1024, '9252', 'ad')...]
我的工作:

resultant_list = []
for _, prefix, nst in cu_list:
    for d, pre, sst in de_list:
        if prefix == pre:
            if sst in ['b', 'l']:
                nst = 'x'+sst
    resultant_list.append((_, prefix, nst))
您可以使用,这往往会使代码更简洁。你的电话是否更优雅

首先处理查找匹配项的问题。内部理解获得
de_list
的第二个元素的列表。外部进行比较:

>>> matches = [i for i in cu_list if i[1] in [j[1] for j in de_list]]
现在修复这些字符串:

>>> result = [(a, b, 'x'+c) if c in ['b', 'l'] else (a, b, c) for a, b, c in matches]
>>> result
[(1024, '9251', 'xb'),
 (1024, '9254', 'xb'),
 (1024, '9253', 'ad'),
 (1024, '9231', 'xl'),
 (1024, '9252', 'ad')]

PS通常只对不使用的变量使用

@AvinashRaj我尝试使用嵌套循环来完成我的工作,但代码看起来很混乱。我想用更好的方式做。我希望一些内置函数可以帮助我清理代码。因此,发布您尝试过的代码,我希望结果列表是这样的:结果列表=[(1024,'9251,'b'),(1024,'9254,'b'),(1024,'9253,'xl'),(1024,'9231,'l'),(1024,'9252,'ad')…]但是通过您的代码片段,它将产生所有的xb和xl。在这种情况下,当且仅当Deu列表中的元组有b或l,那么它应该是xb或xl,否则与Cuu列表中的值相同。嗯,对了,对不起。。。这在理解上更难做到。我认为你的解决方案可能是最清楚的。