Python 从无序的元组集获取路由
我们希望在Python中解决以下问题: 有一个带有圆弧/元组的路由Python 从无序的元组集获取路由,python,routes,tuples,Python,Routes,Tuples,我们希望在Python中解决以下问题: 有一个带有圆弧/元组的路由[i,j]。例如:[(0,10)、(11,0)、(10,11)] 并非所有列表的长度都相同(每个列表可以有x个元组) 这些弧需要成为以下路径[0,10,11,0] 有人知道如何解决这个问题吗?我想这只是一个学习如何使用Python做某些事情的示例?请看下面的代码,了解如何实现这一目标的基本方法。不过,它不是经过优化的代码 # Define a route by the steps you have to take from o
[i,j]
。例如:[(0,10)、(11,0)、(10,11)]
- 并非所有列表的长度都相同(每个列表可以有x个元组)
- 这些弧需要成为以下路径
[0,10,11,0]
有人知道如何解决这个问题吗?我想这只是一个学习如何使用Python做某些事情的示例?请看下面的代码,了解如何实现这一目标的基本方法。不过,它不是经过优化的代码
# Define a route by the steps you have to take from one origin to the
# new destination. These steps are provided as a list of tuples where
# the first element is the origin and the second element is the destination.
steps = [(0,10), (11,0), (10,11)]
# Start with origin 0
route = [0]
# Repeat until no steps left to take
while len(steps) > 0:
# The former destination is the last element of the current route
former_destination = route[-1]
# Browse through all remaining steps
for i, (origin, destination) in enumerate(steps):
# Skip this step if its origin and the former destination don't match
if origin != former_destination:
continue
# Remove the current step
steps.pop(i)
# Add new destination
route.append(destination)
break
print(route)
哪个会打印
[0, 10, 11, 0]
使用字典并在查找节点时删除节点:
nodes=[(0,10)、(11,0)、(10,11)]
d=dict(节点)
链=[0]
而d:
chain.append(d.pop(chain[-1]))
question@Jayjayyy是的,我们总是在0开始和结束。毫无疑问,这非常有帮助。谢谢!