如何在python中结合两组字母而不改变它们的顺序?
例如:
String1: 'PEACH' Set1={'P','E','A','C','H'}
String2: 'DUE'
Set2={'D','U','E'}
Output Set1 union Set2 = {'P','E','A','D','U'}
答案 0 :(得分:2)
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']
答案 1 :(得分:2)
Concat两个字符串,并应用OrderedDict.fromkeys
。将s1
和s2
作为您的字符串:
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(s1+s2))
['P', 'E', 'A', 'C', 'H', 'D', 'U']