Python:在函数中使用函数?

2024-04-20 12:54:44 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,对于赋值,我必须在一个Python文件中创建一组不同的函数。其中一个函数调用输入一个列表(排序列表)和该列表(项目)中的一个字符串。函数所做的是读取列表并从列表中删除指定字符串的任何重复项。你知道吗

def remove_duplicates(sorted_list, item):
    list_real = []
    for x in range(len(sorted_list)-1):
        if(sorted_list[i] == item and sorted_list[i+1] == item):
            list_real = list_real + [item]
            i+1
        else:
            if(sorted_list[i] != item):
                list_real = list_real + [sorted_list[i]]
        i+=1
    return list_real

所以呢 remove_duplicates(['a','a','a','b','b','c'] 'a')将返回['a','b','b','c']

这可能不是最有效的方法,但这不是我的问题。你知道吗

我要定义的下一个函数与上面的函数类似,只是它只接受排序后的列表,并且它必须为每个项而不是指定的项删除重复项。我只知道,必须使用for循环,使remove\u duplicates为给定列表中的每个项运行,但我不知道如何在另一个函数中实际实现一个函数。有人能帮我吗?你知道吗


Tags: 文件函数字符串列表forif排序item
1条回答
网友
1楼 · 发布于 2024-04-20 12:54:44

这很有效:

from itertools import ifilterfalse

def remove_duplicates(sorted_list, item):
    idx = sorted_list.index(item)
    list_real = sorted_list[:idx+1]
    if len(list_real) != len(sorted_list):
        for item in ifilterfalse (lambda x: x is item, sorted_list[idx:]):
            list_real.append(item)
    return list_real

相关问题 更多 >