How to sort a list of interconnected tuples?

lst = [(u'course', u'session'), (u'instructor', u'session'), (u'session', u'trainee'), (u'person', u'trainee'), (u'person', u'instructor'), (u'course', u'instructor')]

I have a list of tuples above, I need to sort it with the following logic .... each element of the 2nd tuple depends on the 1st element, for example. (course, session) β†’ the session depends on the course, etc.

I want the sorted list to be based on the priority of their dependency, the first or less object will be the first, so the output should look like this:

lst = [course, person, instructor, session, trainee]
+3
source share
2 answers

, . wikipedia Kahn ; Python ( , ), pypi ( ), ) ( , ), .

+5

, , , , . Python ( , , ), , http://www.bitformation.com/art/python_toposort.html

- , items , partial_order. lst . , itertools.chain.from_iterable(lst),

import itertools
lst = ...
ordering = topological_sort(itertools.chain.from_iterable(lst), lst)

, , lst.

EDIT. topsort Alex Martelli, lst .

+4

Source: https://habr.com/ru/post/1752393/


All Articles