将字符串排序为相同的单词

2024-04-26 20:32:41 发布

您现在位置:Python中文网/ 问答频道 /正文

word = "help"
scrambled = ['p','e','h','l']

我该如何安排和word一样的顺序?所以皮尔需要帮助。你知道吗

编辑1:

this is for a hangman game, so it would go:
guess 1:
input = "p"
scrambled = ['p']
guess 2:
input = "e"
scrambled = ['p','e']

等等。你知道吗


Tags: game编辑forinputso顺序ishelp
3条回答

list(word)会做得最快。。你知道吗

但是要对scrambled进行排序,可以使用:

sorted(scrambled, key=word.index)

或者,使用就地排序:

scrambled.sort(key=word.index)

只有当word没有重复的字母时,这才起作用。对于scrambled中的每个条目,调用word.index(),返回word中每个字母的索引,然后使用索引对scrambled列表进行排序。你知道吗

演示:

>>> word = "help"
>>> scrambled = ['p','e','h','l']
>>> list(word)
['h', 'e', 'l', 'p']
>>> sorted(scrambled, key=word.index)
['h', 'e', 'l', 'p']

对于重复的字母,可以基于word索引构建键函数:

def make_sort_key(word):
    indices = {}
    for i, c in enumerate(word):
        indices.setdefault(c, []).append(i)
    def key(c):
        return indices[c].pop()
    return key

sorted(scrambled, key=make_sort_key(word))

它为word中的每个字母预先构建索引,并在scrambled列表排序时返回这些索引。你知道吗

演示:

>>> word = 'letters'
>>> scrambled = ['s', 'e', 'l', 'r', 'e', 't', 't']
>>> def make_sort_key(word):
...     indices = {}
...     for i, c in enumerate(word):
...         indices.setdefault(c, []).append(i)
...     def key(c):
...         return indices[c].pop()
...     return key
... 
>>> sorted(scrambled, key=make_sort_key(word))
['l', 'e', 't', 't', 'e', 'r', 's']

我从字面上解释:

>>> word = "help"
>>> scrambled = ['p','e','h','l', 'p','e','h','l', ]
>>> scrambled.sort(key=word.find)
>>> scrambled
['h', 'h', 'e', 'e', 'l', 'l', 'p', 'p']

下面是一个处理重复字母的解决方案:

def make_key(word):
    prev = {}
    def key(c):
        prev[c] = word.index(c, prev.get(c, -1) + 1)
        return prev[c]
    return key

例如:

>>> word = 'lollipop'
>>> scrambled = ['o', 'i', 'l', 'l', 'p', 'p', 'o', 'l']
>>> scrambled.sort(key=make_key(word))
>>> scrambled
['l', 'o', 'l', 'l', 'i', 'p', 'o', 'p']

相关问题 更多 >