删除具有特定重复索引的列表列表,而不保留找到的第一个并保持顺序
Remove lists of list that has a specific duplicate index without keeping the first one found and keeping order
如果我有一个简单的值列表,我可以像这样完全删除重复项:
lines = ['a','b','a']
final_lines = [l for l in lines if lines.count(l) == 1]
输出:
['b']
但是当我有列表列表并且我想专门分析索引 [0]
中的重复值并删除列表(如果存在重复项)时:
lines = [['a','b','c','d'],['e','f','g','h'],['a','j','k','l']]
final_lines = [l for l in lines if lines.count(l[0]) == 1]
final_lines = [l for l in lines if l[0].count(l[0]) == 1]
final_lines = [l for l in lines if l[0].count(lines[0][0]) == 1]
这个选项不是returns这个想要的输出:
[['e','f','g','h']]
信息添加:
创建问题后,我最终遇到了新的尝试:
final_lines = [l for l in lines if l[0].count(lines[0][0]) == 0]
但只有在只有一个索引重复时才有效,如果还有一个像这样:
lines = [['a','b','c','d'],['e','f','g','h'],['e','f','g','h'],['a','j','k','l']]
而不是返回:
[]
Return:
[['e', 'f', 'g', 'h'], ['e', 'f', 'g', 'h']]
一种方法:使用您要比较的每一项的列表:
firsts = [x[0] for x in lines]
final_lines = [l for l in lines if firsts.count(l[0]) == 1]
如果我有一个简单的值列表,我可以像这样完全删除重复项:
lines = ['a','b','a']
final_lines = [l for l in lines if lines.count(l) == 1]
输出:
['b']
但是当我有列表列表并且我想专门分析索引 [0]
中的重复值并删除列表(如果存在重复项)时:
lines = [['a','b','c','d'],['e','f','g','h'],['a','j','k','l']]
final_lines = [l for l in lines if lines.count(l[0]) == 1]
final_lines = [l for l in lines if l[0].count(l[0]) == 1]
final_lines = [l for l in lines if l[0].count(lines[0][0]) == 1]
这个选项不是returns这个想要的输出:
[['e','f','g','h']]
信息添加:
创建问题后,我最终遇到了新的尝试:
final_lines = [l for l in lines if l[0].count(lines[0][0]) == 0]
但只有在只有一个索引重复时才有效,如果还有一个像这样:
lines = [['a','b','c','d'],['e','f','g','h'],['e','f','g','h'],['a','j','k','l']]
而不是返回:
[]
Return:
[['e', 'f', 'g', 'h'], ['e', 'f', 'g', 'h']]
一种方法:使用您要比较的每一项的列表:
firsts = [x[0] for x in lines]
final_lines = [l for l in lines if firsts.count(l[0]) == 1]