python - 如何在不改变顺序的情况下合并python中的两组字母?
例如:
String1: 'PEACH' Set1={'P','E','A','C','H'}
String2: 'DUE'
Set2={'D','U','E'}
Output Set1 union Set2 = {'P','E','A','D','U'}
OrderedDict
数据结构以下代码段显示了一个示例:
>>> from collections import OrderedDict
>>> first_keys = OrderedDict.fromkeys('PEACH')
>>> first_keys.keys()
['P', 'E', 'A', 'C', 'H']
>>> second_keys = OrderedDict.fromkeys('DUE')
>>> second_keys.keys()
['D', 'U', 'E']
>>> first_keys.update(second_keys.items())
>>> first_keys.keys()
['P', 'E', 'A', 'C', 'H', 'D', 'U']
连接两个字符串,然后应用OrderedDict.fromkeys
. 使用s1
和s2
作为您的字符串:
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(s1+s2))
['P', 'E', 'A', 'C', 'H', 'D', 'U']