匹配字符串索引

时间:2014-12-08 17:03:46

标签: python sorting python-3.x

如果我有字符串

s1 = "PHONE" 
s2 = "EHNOP" # this is just s1 that has been alphabetically sorted

如何确定s2索引需要更改以使其等同于s1?我的意思是,s2[0]应为s2[4]s[3]应为s[2]等。

我不想实际排序s2我只需要知道s2的字母应该是哪个索引,以匹配s1

1 个答案:

答案 0 :(得分:0)

s1 = "PHONE"
s2 = "EHNOP"
st = set()

from collections import defaultdict

d = defaultdict(list)
for ind, s in enumerate(s1):
    d[s].append(ind)

for ind, s in enumerate(s2):
    s_ind = d[s].pop(0)
    if s_ind != ind and (ind, s_ind) not in st:
        st.add((s_ind, ind))
print(st)
set([(3, 2), (4, 0)])


s2 = list(s2)

for a, b in st:
    s2[b],s2[a] = s2[a],s2[b]
print("".join(s2))
PHONE

如果你有重复的字母并想重新加入,你将不得不做一些额外的工作,但上面的代码将找到交换索引并找到重复字母的索引: