a_list = [[70,62],[31,62],[62,71],[70,31],[70,71],[31,71]]
我有上面的列表。上面的每个列表都有两个元素,第一个元素始终小于第二个元素(e.x:30< 62对于第一个列表( - 我不比较数字本身(当然30< 62,但是如果列表为(62,30(因此应为62< 30(。因此,根据我的列表,如何有效地列出整个订单列表?我尝试手动编写,但我的代码运行得如此之错误,许多语句
结果应为:
[70,31,62,71]
比较每对列表后。
我尝试使用3对列表作为belows:
sort = []
list = [[48, 33], [56, 33], [56, 48]]
for i in list[:-1]:
for j in list[1:]:
if i[0] == j[1]:
sort.extend([i[0],i[1],j[0]])
break
print(sort)
结果是[56,48,33]但是对于更大的数字,我仍在检查。
>>> from collections import defaultdict
... from operator import itemgetter
...
...
... def solution(pairs_list):
... d = defaultdict(int)
... for a, b in pairs_list:
... d[a]
... d[b] += 1
...
... return [k for k, _ in sorted(d.items(), key=itemgetter(1))]
...
>>> a_list = [[70, 62], [31, 62], [62, 71], [70, 31], [70, 71], [31, 71]]
>>> solution(a_list)
[70, 31, 62, 71]
>>> b_list = [[48, 33], [56, 33], [56, 48]]
>>> solution(b_list)
[56, 48, 33]
您要表达的问题是有向图。您可以使用NetworkX库与这些合作:
代码:
def sort_nodes(node_list):
import networkx as nx
graph = nx.DiGraph(node_list)
sorted_nodes = [y[1] for y in sorted(
(len(neighbors), node) for node, neighbors in graph.pred.items())]
return sorted_nodes
测试代码:
test_data = (
dict(
input=[[70, 62], [31, 62], [62, 71], [70, 31], [70, 71], [31, 71]],
desired_result=[70, 31, 62, 71]),
dict(
input=[[48, 33], [56, 33], [56, 48]],
desired_result=[56, 48, 33]),
)
import networkx as nx
for test in test_data:
nodes = sort_nodes(test['input'])
print(nodes)
assert nodes == test['desired_result']
结果:
[70, 31, 62, 71]
[56, 48, 33]