Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

python - How can I use Yield and Range to get the position and item from a list?

I'd like to implement yield and range to challenge myself and get a better understanding of both. I'm trying to use yield to loop through a function to get a random number within the list. And range used somewhere within as well. The current function below I have isn't currently working.

NumList = [6,9,32,39,61,75,60,63,22,49,26,4,64,54,78,43,1,47,46,17,69,20,85,71,93,28,89,67,14,88,15,73,96,86,55,79,68,76,94,65]

def PenTune(): 
    for NumList in range(1):
        yield random.choice(list(enumerate(NumList)))

for pos, item in PenTune():
       print("pos:", pos, "itemvalue:", item)
question from:https://stackoverflow.com/questions/65886916/how-can-i-use-yield-and-range-to-get-the-position-and-item-from-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following may hint you at what's going on:

numList = [6,9,32,39,61,75,60,63,22,49,26,4,64,54,78,43,1,47,46,17,69,20,85,71,93,28,89,67,14,88,15,73,96,86,55,79,68,76,94,65]

def PenTune(): 
    e = list(enumerate(numList))  # only listify it once
    for _ in range(5):  # or how many random index-value pairs you want
        yield random.choice(e)

for pos, item in PenTune():
    print("pos:", pos, "itemvalue:", item)

pos: 37 itemvalue: 76
pos: 16 itemvalue: 1
pos: 29 itemvalue: 88
pos: 32 itemvalue: 96
pos: 8 itemvalue: 22

A less wasteful implementation:

def PenTune(): 
    for _ in range(5):
        i = random.randint(0, len(numList)-1)
        yield i, numList[i]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...