Python 从数据类型(长字符串、列表、字典、元组)中删除重复项
只能够解决字符串和列表,上面的代码只适用于字符串Python 从数据类型(长字符串、列表、字典、元组)中删除重复项,python,string,list,dictionary,tuples,Python,String,List,Dictionary,Tuples,只能够解决字符串和列表,上面的代码只适用于字符串 无法同时解决字典和所有数据类型的问题您可以使用设置实现相同的结果,然后转换回所需的输出类型 差不多 sample input "AAAAABBBBSSSSS" sample output "ABS" sample input [1,2,4,3,2,2,2] sample output [1,2,4,3] sample input {"hello": 3, "hi":
无法同时解决字典和所有数据类型的问题您可以使用
设置
实现相同的结果,然后转换回所需的输出类型差不多
sample input "AAAAABBBBSSSSS"
sample output "ABS"
sample input [1,2,4,3,2,2,2]
sample output [1,2,4,3]
sample input {"hello": 3, "hi": 1 , "bye" : 2}
sample output {"hello": 1, "hi": 1 , "bye" : 1}
sample input (1,2,3,3,4,4)
sample output (1,2,3,4)
它适用于除字典以外的所有其他类型。对于dictionary,您不清楚要实现什么。这正是您想要的,另一个答案对于字符串和dict没有用处,也跳过了到main类型的转换:
def remove_duplicate(input_parameter):
unique =set(input_parameter)
# Do the type conversion or format
# of output you want
return unique
现在请举例说明:
def remove_duplicates(input_argument):
input_type = type(input_argument)
if input_type is str:
result = ''
for character in input_argument:
if character not in result:
result += character
elif input_type is dict:
result = {}
for key in input_argument:
result[key] = 1 # or any other value you want
else:
result = input_type(set(input_argument))
return result
尝试查看哪些集合是为查找重复项而优化的。因此,您可以将数据类型项添加到集合中,然后使用集合函数查找重复项。要让字典同时找到键和值,请使用
字典\u name.items()
好的,谢谢,让我检查一下是否有办法确定我们的输入是否为哪种数据类型。有人能告诉我为什么我会得到否定票这个平台是为了互相帮助。我不知道如何回答这个问题,那么我还应该问什么呢!你应该阅读如何提问,这样你才知道如何提问。关于上述idk问题,可以使用try except
语句并尝试对数据执行操作,如果出现错误,请检查下一个选项,例如try to.append()
查看数据,并在它无法执行时进行例外,例如,因为它是字典,所以确定谢谢先生,我首先检查输入是否是其中的哪一个,并为每个输入创建一个函数OK谢谢抱歉,我无法更正您的答案我没有足够的声誉字典的输出必须只有每个值对应一个值key@NELSONJOSEPH,一个键在字典中不能重复。@NELSONJOSEPH,你想把每个键的值都赋给1吗?是的,太好了,它有点简化了,我只是为4种类型创建了4个函数,并检查了输入,更好了,先生。谢谢你的帮助
def remove_duplicates(input_argument):
input_type = type(input_argument)
if input_type is str:
result = ''
for character in input_argument:
if character not in result:
result += character
elif input_type is dict:
result = {}
for key in input_argument:
result[key] = 1 # or any other value you want
else:
result = input_type(set(input_argument))
return result
remove_duplicates("AAAAABBBBSSSSS")
# "ABS"
remove_duplicates([1,2,4,3,2,2,2])
# [1,2,4,3]
remove_duplicates({"hello": 3, "hi": 1 , "bye" : 2})
# {"hello": 1, "hi": 1 , "bye" : 1}
remove_duplicates((1,2,3,3,4,4))
# (1,2,3,4)