简体   繁体   English

在Python中执行此操作的最佳方法是什么?

[英]What's the best way to do this in Python?

I have a list of objects where each of them have start and end properties like: 我有一个对象列表,其中每个对象都有startend属性,例如:

Item 0:
Start: 1
End: 12

Item 1:
Start: 6
End: 3

Item 2:
Start: 12
End: 6

I want to order them so that each item's start and end matches with the one that comes before and after itself, in the new list. 我想对它们进行排序,以使每个项目的startend与新列表中之前和之后的内容匹配。

So in this example, it would be: 因此,在此示例中,它将是:

[Item 0] [Item 2] [Item 1]
[1   12] [12   6] [6    3]

It doesn't matter if the whole list was reversed. 整个列表是否颠倒都没关系。

Also there are 2 unrelated lists like above mixed in so I have to form 2 new lists that will have the proper order as shown above. 另外,还有2个不相关的列表(如上述)混在一起,所以我必须形成2个具有正确顺序的新列表,如上所示。

I am just gonna start implementing it "brute-force" so doing a lot of queries to create these lists but I wanted to ask if someone might have a more elegant way to solve this. 我将开始以“蛮力”方式实现它,因此要进行大量查询来创建这些列表,但我想问一问是否有人可以采用更优雅的方式来解决此问题。 I am not sure how common this sort of problem but I remember seeing this before, so maybe there are patterns to deal with this problem. 我不确定这种问题有多普遍,但我记得以前曾见过,所以也许有一些模式可以解决这个问题。

Assuming there are perfect match ups for start/end for each start and end: 假设每个起点和终点都有一个完美的起点/终点匹配:

items_by_start = dict((i.start, i) for i in your_items)

ordered_items = [your_items[0]]
for _ in xrange(len(your_items)-1):
    ordered_items.append(items_by_start[ordered_items[-1].end])

Ordering the elements suggests no duplicate items. 排序元素表明没有重复的项目。 However, with duplicate start s or end s you'd have to be more careful (and more than one solution might be possible). 但是,对于重复的startend您必须格外小心(可能有多个解决方案)。 The problem would be equal to finding Eulerian paths in connected components of an undirected graph, which can be obtained by treating each ( start , end ) pair as a graph edge. 问题将等同于在无向图的连接组件中找到欧拉路径 ,这可以通过将每对( startend )对视为图边来获得。

There are more than enough examples of how it can be implemented in Python on the web. 关于如何在Web上的Python中实现它的例子不胜枚举。 Bear in mind, that it can be done easily in O(m) time, where m is the number of edges. 请记住,可以很容易地在O(m)时间内完成操作,其中m是边数。

Also, an Euclidean path exists if and only if every vertex has an even degree. 同样,当且仅当每个顶点具有偶数度数时,才存在欧几里德路径。 It still holds if you have many components in your graph. 如果图形中有很多组件,它仍然成立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM