Python:使用while或for循环遍历列表

2024-06-30 16:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在不使用字典的情况下连接列表中元组中的值。具体来说,我有一份清单:

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')]

我想用随机元组中的值创建一个列表:

^{pr2}$

如果一个元组的第一个值与newList的最后一个值相同,则从adjList追加该元组的第二个值,因此:

newList = ['1', '0', '3']

然后从ADJ0(“1”)和“列表”中删除(“1”)。在

然后我想重复这个操作,直到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中的元组用完之前,我不知道如何重复最后一段代码。在

提前谢谢你的帮助。在


Tags: 代码列表for字典情况axremove元组
2条回答

adjList上仍有项目时,可以只运行外部while循环。内部循环可以从adjList中选择第一个合适的项,并将结果追加到newList。如果内循环找不到合适的项目,则应终止外循环。在

以下是上述示例:

import random

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 = list(adjList.pop(random.randint(0, len(adjList) - 1)))

while adjList:
    for i, (src, dest) in enumerate(adjList):
        if src == newList[-1]:
            del adjList[i]
            newList.append(dest)
            break
    else:
        break

print('Result: {}'.format(newList))
print('Remaining: {}'.format(adjList))

输出:

^{pr2}$

我不太确定下面的代码是否适用于您的需要,但我认为您应该能够做您想做的事情,只需对代码做很少的更改。在

我添加了一个while循环,该循环每次结构发生变化时都会运行(基本上,每次元组的第一项与newList中的最后一项匹配时):

#!/usr/bin/env python
import random

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])

changes_made = True
while changes_made:
    changes_made = False
    for item in adjList:
        if item[0] == newList[-1]:
            newList.append(item[-1])
            adjList.remove(item)
            changes_made = True
            break

print newList

相关问题 更多 >