📜  从Python中的给定字符串中删除所有重复项

📅  最后修改于: 2022-05-13 01:55:20.168000             🧑  作者: Mango

从Python中的给定字符串中删除所有重复项

我们得到一个字符串,我们需要从中删除所有重复项吗?如果字符顺序很重要,输出会是什么?

例子:

此问题已有解决方案,请参阅 Remove all duplicates from a given 字符串。
方法一:

from collections import OrderedDict 
  
# Function to remove all duplicates from string 
# and order does not matter 
def removeDupWithoutOrder(str): 
  
    # set() --> A Set is an unordered collection 
    #         data type that is iterable, mutable, 
    #         and has no duplicate elements. 
    # "".join() --> It joins two adjacent elements in 
    #             iterable with any symbol defined in 
    #             "" ( double quotes ) and returns a 
    #             single string 
    return "".join(set(str)) 
  
# Function to remove all duplicates from string 
# and keep the order of characters same 
def removeDupWithOrder(str): 
    return "".join(OrderedDict.fromkeys(str)) 
  
# Driver program 
if __name__ == "__main__": 
    str = "geeksforgeeks"
    print ("Without Order = ",removeDupWithoutOrder(str)) 
    print ("With Order = ",removeDupWithOrder(str)) 

输出:

Without Order =  egfkosr
With Order    =  geksfor

方法二:

def removeDuplicate(str):
    s=set(str)
    s="".join(s)
    print("Without Order:",s)
    t=""
    for i in str:
        if(i in t):
            pass
        else:
            t=t+i
        print("With Order:",t)
      
str="geeksforgeeks"
removeDuplicate(str)

输出:

Without Order: rofgeks
With Order: geksfor

OrderedDict 和 fromkeys() 做什么?

OrderedDict 是一个字典,它记住首先插入的键的顺序。如果新条目覆盖现有条目,则原始插入位置保持不变。

例如见下面的代码片段:

from collections import OrderedDict
  
ordinary_dictionary = {}
ordinary_dictionary['a'] = 1
ordinary_dictionary['b'] = 2
ordinary_dictionary['c'] = 3
ordinary_dictionary['d'] = 4
ordinary_dictionary['e'] = 5
  
# Output = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
print (ordinary_dictionary)    
  
ordered_dictionary = OrderedDict()
ordered_dictionary['a'] = 1
ordered_dictionary['b'] = 2
ordered_dictionary['c'] = 3
ordered_dictionary['d'] = 4
ordered_dictionary['e'] = 5
  
# Output = {'a':1,'b':2,'c':3,'d':4,'e':5}
print (ordered_dictionary)      

fromkeys()创建一个新字典,其中键来自 seq,值设置为 value 并返回键列表, fromkeys(seq[, value])是 fromkeys() 方法的语法。

参数 :

  • seq :这是用于准备字典键的值列表。
  • value :这是可选的,如果提供,则 value 将设置为此值。

例如见下面的代码片段:

from collections import OrderedDict
seq = ('name', 'age', 'gender')
dict = OrderedDict.fromkeys(seq)
  
# Output = {'age': None, 'name': None, 'gender': None}
print (str(dict)) 
dict = OrderedDict.fromkeys(seq, 10)
  
# Output = {'age': 10, 'name': 10, 'gender': 10}
print (str(dict))