我有像这样的字符串
list = ['stro', 'asdv', '', 'figh']我使用的是:
for ele in sorted(list):
print(ele)我需要这样的输出:
asdv
figh
stro
empty space element from list最后,我需要获取空字符串,并将其他字符串按顺序排序
如果我做一个反向排序,我想得到的输出是:
empty string element
stro
figh
asdv发布于 2019-09-25 18:26:42
您可以先打印非空排序的元素,然后再打印空元素:
from itertools import chain
for element in chain(sorted(filter(bool, my_list)), filter(lambda x: not x, my_list)):
print(element)发布于 2019-09-25 19:17:40
您需要为比较定义自己的键。您希望空字符串放在最后。我们可以利用这样一个事实,一个空字符串是假的。
>>> bool('a')
True
>>> bool('')
FalseTrue比False大,所以非空字符串将在空字符串之后排序,但我们需要的是另一种方式。
>>> not 'a'
False
>>> not ''
True作为第二个排序标准,我们将获取字符串本身。为此,我们必须比较元组(not s, s),其中s是字符串。
我们可以使用key参数和一个lambda函数将其提供给sorted。
>>> data = ['stro', 'asdv', '', 'figh']
>>> print(sorted(data, key=lambda s: (not s, s)))
['asdv', 'figh', 'stro', '']如果希望反转,请添加reverse参数。
>>> print(sorted(data, key=lambda s: (not s, s), reverse=True))
['', 'stro', 'figh', 'asdv']请注意,我将变量list重命名为data。如果使用list,就会覆盖内置的list,即使是在示例中,这也不是一个好主意。
https://stackoverflow.com/questions/58095974
复制相似问题