如何通过使用列表理解或任何其他方法使我的函数更简洁?

问题描述

上下文:我有一个列表列表,我正在尝试删除重复的条目。列表列表按子列表中的第一个元素排序。当函数遇到子列表的第一次出现时,函数将该子列表附加到“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)]

您不应该在列表推导式中使用 continuereturn,查看 here 了解更多信息

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...