簡體   English   中英

Python:使用while或for循環迭代列表

[英]Python: using while or for loop to iterate through an lists

我試圖連接列表中的元組中的值而不使用字典。 具體來說,我有這個清單:

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 NO LONGER中的最后一個值對應於來自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中用完元組。

在此先感謝您的幫助。

您可以只運行外部while循環,而adjList上仍有項目。 內循環可以從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))

輸出:

Result: ['4', '2', '1', '0', '3', '2', '6', '5', '4']
Remaining: [('7', '9'), ('8', '7'), ('9', '6'), ('6', '8')]

我不太確定以下代碼是否適用於您的需求,但我認為您應該可以通過對代碼進行很少的更改來執行您想要的操作。

我添加了一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM