在python中编写一个删除重复项的函数

2024-05-18 15:32:44 发布

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

编写一个名为remove\u duplicates的函数,它将采用一个名为string的参数。此字符串输入只包含a-z之间的字符

函数应删除字符串中所有重复的字符,并返回一个包含两个值的元组:

一个新字符串,只包含唯一的、已排序的字符。在

删除的重复项总数。在

例如:

remove_duplicates('aaabbbac') => ('abc', 5)

remove_duplicates('a') => ('a', 0)

remove_duplicates('thelexash') => ('aehlstx', 2)

这是我的解决方案,我是python新手:

^{pr2}$

我可能做错了什么?这是下面的错误

您的代码中存在错误/错误 结果: /bin/sh:1:python/nose2/bin/nose2:未找到

谢谢。在


Tags: 函数字符串参数stringbin排序错误字符
3条回答

这个很好用。输出应该被排序。在

def remove_duplicates(string):
   new_string = "".join(sorted(set(string)))
   if new_string:
     return (new_string, len(string)-len(new_string))
   else:
     print "Please provide only alphabets"

无需包括:

^{pr2}$

从我正在做的一个测试中收到同样的错误,我觉得错误不是来自您的,而是测试人员的

由于顺序不重要,您可以使用

string = raw_input("Please enter a string...")

def remove_duplicates(string):
   new_string = "".join(set(string))
   if new_string:
     return (new_string, len(string)-len(new_string))
   else:
     print "Please provide only alphabets"

 remove_duplicates(string)

Please enter a string...aaabbbac
Out[27]: ('acb', 5)

set()将在字符串中创建一组唯一的字母,“.join()将以任意顺序将字母连接回字符串。在

相关问题 更多 >

    热门问题