【发布时间】: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
输入:
Alpha = ['d', 'c', 'a', 'b']
words = ['dda', 'bdb', 'adc', 'cdd']
如何按 Alpha 的顺序对单词进行排序以获得以下结果?
words = ['dda', 'cdd', 'adc', 'bdb']
你能告诉我怎么做吗?
我在这里尝试对列表进行排序,而不是对字典键进行排序
【问题讨论】:
标签: python python-2.7
这将根据您在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]))
【讨论】:
您可以使用带键的排序功能:
>>> Alpha = ['d', 'c', 'a', 'b']
>>> words = ['dda', 'bdb', 'adc', 'cdd']
>>> sorted(words, key=lambda x:Alpha.index(x[0]))
['dda', 'cdd', 'adc', 'bdb']
【讨论】:
你可以用这个,它会根据首字母的字母索引排序。
alpha = ['d', 'c', 'a', 'b']
words = ['dda', 'bdb', 'adc', 'cdd']
words.sort(key=lambda x: alpha.index(x[0]))
输出:
“dda”“cdd”“adc”“bdb”
【讨论】: