Python:在函数中使用函数?
因此,对于赋值,我必须在一个Python文件中创建一组不同的函数。其中一个函数调用输入列表(排序列表)和该列表(项目)中的字符串。该函数所做的是读取列表并从列表中删除指定字符串的任何重复项Python:在函数中使用函数?,python,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]
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
所以
删除重复项(['a','a','a','b','b','c']'a')
将返回['a','b','b','c']
这样做可能不是最有效的方式,但这不是我的问题
我必须定义的下一个函数与上面的函数类似,只是它只接受排序列表,并且它必须删除每个项的重复项,而不是指定的项。我知道的唯一一件事是,您必须使用for循环,使remove_duplicates为给定列表中的每个项运行,但我不知道如何在另一个函数中实际实现一个函数。有人能帮我吗?这很有效:
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
你就这么做吧。在另一个函数中编写函数没有特殊的语法。您只需像编写其他代码块一样编写它。这与在另一个if语句中缩进if语句,或在外部语句中嵌套另一个for循环没有什么不同。对于不懂函数的人来说,导入itertools似乎太过分了