如何在python中先打印空字符串的排序列表

2024-04-20 09:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子

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

Tags: 字符串infor排序spaceelementlistempty
2条回答

您需要为比较定义自己的键。你最后想要空字符串。我们可以用一个事实,一个空字符串是假的。你知道吗

>>> bool('a')
True
>>> bool('')
False

TrueFalse大,所以非空字符串将在空字符串之后排序,但我们需要相反的方法。你知道吗

>>> 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,则覆盖内置的^{},即使在示例中,这也是一个坏主意。你知道吗

您可以先打印未排序为空的元素,然后打印空元素:

from itertools import chain

for element in chain(sorted(filter(bool, my_list)), filter(lambda x: not x, my_list)):
    print(element)

相关问题 更多 >