在列表的开头和结尾强制执行项目 [英] Enforce items at beginning and end of list
问题描述
如何修改此列表,以使所有p's
出现在开头,q's
出现在末尾,并且中间的值按字母顺序排序?
How can I modify this list so that all p's
appear at the beginning, the q's
at the end, and the values in between are sorted alphabetically?
l = ['f','g','p','a','p','c','b','q','z','n','d','t','q']
所以我想拥有:
['p','p','a','b','c','d','f','g','n','t','z','q','q']
推荐答案
您可以使用 sorted
和以下key
:
sorted(l, key = lambda s: (s!='p', s=='q', s))
['p', 'p', 'a', 'b', 'c', 'd', 'f', 'g', 'n', 't', 'z', 'q', 'q']
说明
为了更好地了解其工作方式,以下列表理解旨在在进行比较之前复制从key
参数中定义的lambda
函数返回的内容:
To get a better idea of how this is working, the following list comprehension aims to replicate what is being returned from the lambda
function defined in the key
argument prior to making comparisons:
t = [(s!='p', s=='q', s) for s in pl]
print(t)
[(True, False, 'f'),
(True, False, 'g'),
(False, False, 'p'),
(True, False, 'a'),
(False, False, 'p'),
(True, False, 'c'),
(True, False, 'b'),
(True, True, 'q'),
(True, False, 'z'),
(True, False, 'n'),
(True, False, 'd'),
(True, False, 't'),
(True, True, 'q')]
这将是key
,用于对列表中的项目进行排序,如文档:
This will then be the key
to be used to sort the items in the list, as mentioned in the documentation:
key参数的值应该是一个采用单个参数并返回用于排序目的键的函数.
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.
因此,考虑到False = 0
和True = 1
,在对这个元组列表进行排序时,结果如下:
So taking into account that False = 0
and True = 1
, when this list of tuples is sorted the result will be the following:
sorted(t)
[(False, False, 'p'),
(False, False, 'p'),
(True, False, 'a'),
(True, False, 'b'),
(True, False, 'c'),
(True, False, 'd'),
(True, False, 'f'),
(True, False, 'g'),
(True, False, 'n'),
(True, False, 't'),
(True, False, 'z'),
(True, True, 'q'),
(True, True, 'q')]
这篇关于在列表的开头和结尾强制执行项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!