Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 匹配字符串索引_Python_Sorting_Python 3.x - Fatal编程技术网

Python 匹配字符串索引

Python 匹配字符串索引,python,sorting,python-3.x,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 s1 = "PHONE" s2 = "EHNOP" st = set() from collections import

如果我有条件的话

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

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

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

您的代码在哪里,它到底有什么问题?我的问题是我问题的一个极其简化的版本,我的实际代码大约是50行,包括根据字符串对列表进行排序。把它贴出来是没有用的。然后把它删减到a。你的要求也很模糊。变化意味着什么?字符串总是有相同的字母吗?