任何人都可以在python中使这个功能?让我明白

时间:2017-10-02 04:03:45

标签: python

我正在尝试对字符串列表进行排序,在打印b c直到z之前,它应首先打印所有“x” 这段代码有效,但我希望它在函数风格中让我更了解它

words.sort(key=lambda x: (x[0] != 'x', x))

1 个答案:

答案 0 :(得分:3)

这都与两个事实有关。

  1. 元组按索引0排序,然后按索引1排序,然后按索引N排序。
  2. 按升序(向前)顺序排序时,在True之前进行错误排序。
  3. def sort_x_as_first(words):
        things_to_actually_sort = []
        for word in words:
            if word[0] == 'x':
                things_to_actually_sort.append((False, word))
            else:
                things_to_actually_sort.append((True, word))
        # Our things_to_actually_sort has a bunch of tuples where they are
        # (True, word) if the word does not start with x
        # (False, word) if the word does start with x
        temp_sorted_things = sorted(things_to_actually_sort)
        # When applying the sort, the False go first, then the True values after since tuples sort by index 0 first.  For each group of False (the x's) those are then sorted by word.  Same goes for the group of True values.
        sorted_things = []
        for thing in temp_sorted_things:
            sorted_things.append(thing[1])
    
        return sorted_things