问题描述
上下文:我有一个列表列表,我正在尝试删除重复的条目。列表列表按子列表中的第一个元素排序。当函数遇到子列表的第一次出现时,函数将该子列表附加到“non_duplicate_list”。如果该函数遇到具有相同第一个元素的另一个子列表,则继续。
问题:我有一个完美运行的函数,但我觉得它太长了。有没有办法缩短/使代码更简洁?也许使用列表理解?
功能如下:
def remove_duplicates(data_set):
non_duplicate_list = []
for row in data_set:
app_name = row[0]
if any(app_name in sublist for sublist in non_duplicate_list):
continue
else:
non_duplicate_list.append(row)
我尝试这样做是为了使函数更简洁,但是没有用:
def remove_the_dupes(data_set):
non_duplicate_list = [continue if any(row[0] not in sublist for sublist in non_duplicate_list) else non_duplicate_list.append(row) for row in data_set]
return non_duplicate_list
如果可能,请提供我的函数的任何缩短版本。非常感谢!
解决方法
这应该有效
not_duplicate_list = [row for row in datset if not any(row[0] in sublist for sublist in non_duplicate_list)]
您不应该在列表推导式中使用 continue
和 return
,查看 here 了解更多信息