【发布时间】:2017-03-05 01:48:17
【问题描述】:
我正在尝试在不使用字典的情况下连接列表中元组中的值。具体来说,我有这个列表:
adjList = [('0', '3'), ('1', '0'), ('3', '2'), ('4', '2'), ('5', '4'), ('7', '9'),
('8', '7'), ('9', '6'), ('2', '1'), ('2', '6'), ('6', '5'), ('6', '8')]
我想用随机元组中的值创建一个列表:
newList = ['1', '0']
如果该元组的第一个值与 newList 的最后一个值相同,则从 adjList 中附加该元组的第二个值,因此:
newList = ['1', '0', '3']
然后从 adjList 中删除 ('1', '0') 和 ('0', '3')。
然后我想重复这个动作,直到 newList 中的最后一个值不再对应于 adjList 中元组的第一个值。我在找出可以做到这一点的 while 或 for 循环的逻辑组合时遇到了很多麻烦,我们将不胜感激。
到目前为止我的代码:
adjList = [('0', '3'), ('1', '0'), ('3', '2'), ('4', '2'), ('5', '4'), ('7', '9'),
('8', '7'), ('9', '6'), ('2', '1'), ('2', '6'), ('6', '5'), ('6', '8')]
firstNode = random.choice(adjList)
newList = []
newList.append(firstNode[0])
newList.append(firstNode[1])
adjList.remove(firstNode)
## I need to repeat the following block of code:
for ax,bx in adjList:
if newList[-1] == ax:
adjList.remove((ax,bx))
newList.append(bx)
break
一切都按应有的方式工作,但当然我最后只能在 newList 中获得 3 个值。在我用完 adjList 中的元组之前,我无法完全弄清楚如何重复最后的代码块。
提前感谢您的帮助。
【问题讨论】:
-
adjList中有很多可能的元组可供选择的情况如何?假设随机选择的元组是('9', '6')newList的正确值是多少? -
newList 的正确值为 ['9', '6', '5']。只取第一个具有匹配值的元组就可以了。
-
我想如果你不选择随机节点会更容易调试。
-
随机节点与我需要重复的代码块无关。如果这更简单,可以将其视为两个起始列表:adjList 已发布,newList = ['1', '0'],然后我需要从那里开始,匹配值并将它们添加到 newList。
标签: python list while-loop