我是 python 的新手,希望有人能帮助我解决这个问题。我需要对字符串列表进行排序:
s = ['status', 'value', 'place', 'tag']
我需要以排序后的列表如下所示的方式进行排序:
s_sorted = ['tag', 'place', 'status', 'value']
在排序词中,特定字符串 'tag'
需要始终位于前面,其余字符串将被排序。我试图想出一个可以让我这样做的比较器。但到目前为止我还没有做到这一点。如果有人有解决此类问题的经验,如果您能分享一些想法,我将不胜感激。
最佳答案
s = ['status', 'value', 'place', 'tag']
s_sorted = sorted(s, key=lambda x:(x!='tag', x))
key
生成一个元组,如果元素不是 'tag'
,则第一个元素为 bool 值。 sort
按第一个元素排序,然后是第二个元素。这样 tag
总是排在第一位,因为 False
排在 True
之前。
对于剩余元素 - 不等于 'tag'
- 排序通常在第二个元组元素上完成,这是对值本身的字典顺序字符串排序。
来自排序
documentation :
key
specifies a function of one argument that is used to extract a comparison key from each list element:key=str.lower
. The default value isNone
(compare the elements directly).
关于python - 在python中对字符串列表进行排序,以便特定字符串(如果存在)首先出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23090664/