我正在尝试对字符串列表进行排序,在打印b c直到z之前,它应首先打印所有“x” 这段代码有效,但我希望它在函数风格中让我更了解它
words.sort(key=lambda x: (x[0] != 'x', x))
答案 0 :(得分: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