我们得到了一个字符串,我们需要删除其中的所有重复项吗?如果角色的顺序很重要,那么输出会是什么? 例如:
null
Input : geeksforgeeks Output : efgkos
此问题已有解决方案,请参考 删除给定字符串中的所有重复项 . 方法1:
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
方法2:
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()方法的语法。
参数:
- 如下: 这是用于准备字典键的值列表。
- 价值: 这是可选的,如果提供,则该值将设置为该值。
例如,请参见下面的代码片段:
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 )) |
本文由 沙申克·米什拉(古卢) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END