在Python中使用自定义排序参数排序列表的最佳方式是什么?(What is the best way to sort list with custom sorting parameters in P

编程入门 行业动态 更新时间:2024-10-18 01:35:03
在Python中使用自定义排序参数排序列表的最佳方式是什么?(What is the best way to sort list with custom sorting parameters in Python?)

我有一系列看起来像这样的列表:

li1 = ['a.1', 'b.9', 'c.8', 'd.1', 'e.2'] li2 = ['a.4', 'b.1', 'c.2', 'd.2', 'e.4']

我怎样才能重新排列每个列表中的项目,以便第一个项目是'b.something'? 对于上面的例子:

li1 = ['b.9', 'a.1', 'c.8', 'd.1', 'e.2'] li2 = ['b.1', 'a.4', 'c.2', 'd.2', 'e.4']

在第一项之后维护订单并不重要。 谢谢您的帮助。

I have a series of lists that looks like this:

li1 = ['a.1', 'b.9', 'c.8', 'd.1', 'e.2'] li2 = ['a.4', 'b.1', 'c.2', 'd.2', 'e.4']

How can I rearrange the items in each list so that the first item is 'b.something'? For the example above:

li1 = ['b.9', 'a.1', 'c.8', 'd.1', 'e.2'] li2 = ['b.1', 'a.4', 'c.2', 'd.2', 'e.4']

Maintaining the order after the first item isn't important. Thanks for the help.

最满意答案

重新排列每个列表中的项目,以便第一个项目是'b.something'

在第一项之后维护订单并不重要。

那么这不是排序。 从概念上讲,你只是想把这个元素放在前面。

换句话说,你需要一个由该元素组成的列表,后面是不是该元素的所有内容。 对于存在多个b.something的情况b.something ,注意我们不关心发生了什么,只要第一个元素是b.something ,我们可以重新解释:满足条件(“以b.开始”),接着是每个不满足条件的元素。 (这有时称为分区 ;例如,参见C ++中的std::partition 。)

在Python中,这与使用列表解析来描述这两个列表组件并将它们粘在一起一样简单:

[x for x in li if x.startswith('b.')] + [x for x in li if not x.startswith('b.')]

......或者你可以假装你正在排序,只是在应用了key后,只有一组元素只有两个值,然后应用相应的key ,如Ignacio Vasquez-Abrams的答案。

rearrange the items in each list so that the first item is 'b.something'

Maintaining the order after the first item isn't important.

That isn't sorting, then. Conceptually, you're just trying to bring that element to the front.

In other words, you want a list that consists of that element, followed by everything that isn't that element. Fudging this a little for the case where there are multiple b.somethings, and noting that we don't care what happens as long as the first element is a b.something, we can rephrase that: a list of every element meeting the condition ("starts with b."), followed by every element not meeting the condition. (This is sometimes called partitioning; see for example std::partition in C++.)

In Python, this is as simple as describing those two list-components with list comprehensions and sticking them together:

[x for x in li if x.startswith('b.')] + [x for x in li if not x.startswith('b.')]

...Or you can pretend that you're sorting, just with a bunch of elements that really only have two values after the key is applied, and apply the appropriate key, as in Ignacio Vasquez-Abrams' answer.

更多推荐

本文发布于:2023-08-07 07:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1462715.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   参数   方式   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!