我需要通过比较它们的特定索引值来比较两个大的元组列表。
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_list中所有元素的新列表,如果比较成功,则更新cu_list中元素的值。
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))
答案 0 :(得分:0)
您可以使用list comprehensions执行此操作,这可能会使代码更加简洁。你的电话是否更优雅。
首先处理找到匹配项。内部理解得到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它只是将_
用于您不使用的变量。