【问题标题】:How to a sort list in the given alphabetical order using python?如何使用python按给定的字母顺序对列表进行排序?
【发布时间】:2017-04-29 11:03:50
【问题描述】:

输入:

Alpha = ['d', 'c', 'a', 'b']
words = ['dda', 'bdb', 'adc', 'cdd']

如何按 Alpha 的顺序对单词进行排序以获得以下结果?

words = ['dda', 'cdd', 'adc', 'bdb']

你能告诉我怎么做吗?

我在这里尝试对列表进行排序,而不是对字典键进行排序

【问题讨论】:

标签: python python-2.7


【解决方案1】:

这将根据您在alpha 中指定的顺序按字典顺序对单词进行排序,方法是为每个单词(Python then compares lexicographically)制作索引列表

def sort_key(w):
    return [alpha.index(ch) for ch in w]

words.sort(key=sort_key)

可能有更有效的解决方案将密钥存储在哈希中(如the answer to this question)。

另一种方法是将您的alpha 转换为string.translate 转换表。

ascii_characters = ''.join(chr(i) for i in range(256))
translation = string.maketrans(''.join(alpha), ascii_characters[:len(alpha)])
words.sort(key=lambda w: w.translate(translation))

这种方式的一个优点是您可以将翻译放入字典中(可能)更快。

order = {w: w.translate(translation) for w in words}
words.sort(key=lambda w: order[w]))

【讨论】:

    【解决方案2】:

    您可以使用带键的排序功能:

    >>> Alpha = ['d', 'c', 'a', 'b']
    >>> words = ['dda', 'bdb', 'adc', 'cdd']
    >>> sorted(words, key=lambda x:Alpha.index(x[0]))
    ['dda', 'cdd', 'adc', 'bdb']
    

    【讨论】:

    • 尝试不同的单词组合,我认为它不会起作用
    • words = ['dda', 'dbdb', 'dadc', 'dcdd']
    • 好的,排序应该通过整个单词,而不仅仅是第一个字符
    【解决方案3】:

    你可以用这个,它会根据首字母的字母索引排序。

    alpha = ['d', 'c', 'a', 'b']
    words = ['dda', 'bdb', 'adc', 'cdd']
    words.sort(key=lambda x: alpha.index(x[0]))
    

    输出:

    “dda”“cdd”“adc”“bdb”

    【讨论】:

    • 尝试不同的单词组合,我认为它不会起作用
    • 试试pythontutor.com/visualize.html#mode=edit,然后给我看一个例子:)
    • @Beri OP 想要基于 alpha 的字典排序,它不应该只限于第一个字符。
    • 你只用第一个字母排序,请用所有字符排序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多