【问题标题】:How can I make my function more concise by using list comprehension or any other method?如何通过使用列表理解或任何其他方法使我的函数更简洁?
【发布时间】:2021-06-20 10:07:56
【问题描述】:

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

然后我收到一条关于错误语法的错误消息

如果可能,请提供我的函数的任何缩短版本。非常感谢!

【问题讨论】:

    标签: python list function list-comprehension


    【解决方案1】:

    这应该可以工作

     not_duplicate_list = [row for row in datset if not any(row[0] in sublist for sublist in non_duplicate_list)]
    

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

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多