简体   繁体   中英

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

I am trying to connect values in tuples in a list without using a dictionary. Specifically, I have this list:

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

and I would like to create a list with the values from a random tuple:

newList = ['1', '0']

then append the second value of a tuple from adjList if the first value of that tuple is the same as the last value of newList, thus:

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

Then delete ('1', '0') and ('0', '3') from adjList.

THEN I want to repeat this action until the last value in newList NO LONGER corresponds to the first value of a tuple from adjList. I am having a lot of trouble figuring out a logical combination of while or for loops that can do this, and any help would be appreciated.

My code so far:

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

Everything works the way it should, but of course I am only getting 3 values in newList at the end. I can't quite work out how to repeat that final block of code until I run out of tuples in adjList.

Thanks in advance for any help.

You could just run the outer while loop while there are items still on the adjList . The inner loop could pick the first suitable item from adjList and append the result to newList . In case the inner loop can't find suitable item the outer loop should be terminated.

Here's a sample of the above:

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

Output:

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

I'm not very sure whether the following code will apply to your needs, but I think you should be able do what you want with very few changes to your code.

I've added a while loop that runs every time there's a change in the structure (basically, every time that a tuple whose first item matches the last item in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM