我有一系列看起来像这样的列表:
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.
更多推荐
发布评论