📜  按长度排序列表python(1)

📅  最后修改于: 2023-12-03 15:25:54.917000             🧑  作者: Mango

Python中按长度排序列表

有时候我们需要将一个列表按照元素的长度进行排序,这时可以使用Python中的sort函数,并在key参数中传入len函数。

以下是一个示例代码:

words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
words.sort(key=len)
print(words)

输出结果:

['date', 'apple', 'cherry', 'banana', 'elderberry']

在这个例子中,我们将words列表按元素的长度进行排序,date的长度是4,apple的长度是5,cherry的长度是6,依次类推。

另外,如果需要逆序排序,可以在sort函数中传入参数reverse=True,如下所示:

words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
words.sort(key=len, reverse=True)
print(words)

输出结果:

['elderberry', 'banana', 'cherry', 'apple', 'date']

在这个例子中,我们将words列表按元素的长度进行逆序排序。