排序列表(自己定义的值,其他值)

时间:2019-03-21 07:32:45

标签: python list sorting

我有很多列表,我知道这些列表将包含几个已知和几个未知(即变化)的条目。现在,我希望对列表进行排序,以使预期的条目以预定义的顺序移至开头,而其他条目则以其原始顺序或理想情况下按字母顺序移至末尾。

例如,我有如下列表:

l1 = ['Agree', 'Neither agree nor disagree', 'some random answer', 'Strongly agree', 'Disagree', 'Strongly disagree']
l2 = ['Agree', '-99', 'Neither agree nor disagree', 'Strongly agree', 'Disagree', 'Strongly disagree']
l3 = ['Other', 'Agree', 'Neither agree nor disagree', 'Strongly agree', 'Disagree', 'Strongly disagree']
l4 = ['Agree', 'Neither agree nor disagree', 'Strongly agree', 'Disagree', 'Strongly disagree', 'Answer declined']

我希望所有列表都以预定义的方式排序:

l_out = ['Strongly agree', 'Agree', 'Neither agree nor disagree', 'Disagree', 'Strongly disagree', 'X', 'Y', 'Z']`

用X,Y和Z替换所有列表中不存在的各种元素。

我找不到解决此问题的方法,手动遍历列表似乎太麻烦了,无法成为最有效的解决方案。希望得到任何指教-预先感谢您! :)

2 个答案:

答案 0 :(得分:3)

sorted(list_to_sort, key=ranking_list.index)

ranking_list包含您希望元素出现的顺序(即问题中的l_out)。

您还可以为不在排名列表中的值指定默认行为,但这需要更复杂的键:

rank_list = [...]  # Fill as needed

def rank(e, ranking=rank_list):
    try:
        return ranking.index(e)
    except ValueError:  # e was not in the ranking list
        return len(ranking)

sorted(list_to_sort, key=rank)

答案 1 :(得分:2)

>>> l_out = ['Strongly agree', 'Agree', 'Neither agree nor disagree', 'Disagree', 'Strongly disagree']
>>> l1 = ['Agree', 'Neither agree nor disagree', 'some random answer', 'Strongly agree', 'Disagree', 'Strongly disagree']
>>> tmp1 = {k:v for v, k in enumerate(l_out)}
>>> l1.sort(key = lambda x: tmp1.get(x, len(tmp1) + 1))
>>> l1
['Strongly agree', 'Agree', 'Neither agree nor disagree', 'Disagree', 'Strongly disagree', 'some random answer']