【问题标题】:why yield is used in for loop为什么在 for 循环中使用 yield
【发布时间】:2020-06-26 12:19:28
【问题描述】:

*yield 在以下代码中的用途*
以下程序的这些部分。我对生成器函数和产量有一些了解,但不知道它在 for 循环中是如何工作的。

for i in range(len(lengthList) - 1):
        for j in range(len(lengthList) - i - 1):
            if(lengthList[j] > lengthList[j + 1]):
                lengthList[j] , lengthList[j + 1] = lengthList[j + 1] , lengthList[j]
                barList[j], barList[j + 1] = barList[j + 1] , barList[j]
                swap(barList[j + 1] , barList[j])
                yield 

这里是完整的代码

这是为了做空算法可视化

import tkinter as tk
import random

交换两个将被动画化的条的功能

def swap(pos_0, pos_1):
    bar11, _, bar12, _ = canvas.coords(pos_0)
    bar21, _, bar22, _ = canvas.coords(pos_1)
    canvas.move(pos_0, bar21-bar11, 0)
    canvas.move(pos_1, bar12-bar22, 0)

worker = None 

#Insertion Sort
def _insertion_sort():
    global barList
    global lengthList

    for i in range(len(lengthList)):
        cursor = lengthList[i]
        cursorBar = barList[i]
        pos = i

        while pos > 0 and lengthList[pos - 1] > cursor:
            lengthList[pos] = lengthList[pos - 1]
            barList[pos], barList[pos - 1] = barList[pos - 1], barList[pos]
            swap(barList[pos],barList[pos-1])   
            yield                                      
            pos -= 1                                   

        lengthList[pos] = cursor
        barList[pos] = cursorBar
        swap(barList[pos],cursorBar)

冒泡排序

def _bubble_sort():
    global barList
    global lengthList

    for i in range(len(lengthList) - 1):
        for j in range(len(lengthList) - i - 1):
            if(lengthList[j] > lengthList[j + 1]):
                lengthList[j] , lengthList[j + 1] = lengthList[j + 1] , lengthList[j]
                barList[j], barList[j + 1] = barList[j + 1] , barList[j]
                swap(barList[j + 1] , barList[j])
                yield

选择排序

def _selection_sort():
    global barList    
    global lengthList

    for i in range(len(lengthList)):
        min = i
        for j in range(i + 1 ,len(lengthList)):
            if(lengthList[j] < lengthList[min]):
                min = j
        lengthList[min], lengthList[i] = lengthList[i] ,lengthList[min]
        barList[min] , barList[i] = barList[i] , barList[min]
        swap(barList[min] , barList[i])        
        yield

触发函数

def insertion_sort():     
    global worker
    worker = _insertion_sort()
    animate()

def selection_sort():     
    global worker
    worker = _selection_sort()
    animate()

def bubble_sort():     
    global worker
    worker = _bubble_sort()
    animate()    

动画功能

def animate():      
    global worker
    if worker is not None:
        try:
            next(worker)
            window.after(10, animate)    
        except StopIteration:            
            worker = None
        finally:
            window.after_cancel(animate)

生成数据的生成器函数

def generate():
    global barList
    global lengthList
    canvas.delete('all')
    barstart = 5
    barend = 15
    barList = []
    lengthList = []

    #Creating a rectangle
    for bar in range(1, 60):
        randomY = random.randint(1, 360)
        bar = canvas.create_rectangle(barstart, randomY, barend, 365, fill='yellow')
        barList.append(bar)
        barstart += 10
        barend += 10

    #Getting length of the bar and appending into length list
    for bar in barList:
        bar = canvas.coords(bar)
        length = bar[3] - bar[1]
        lengthList.append(length)

    #Maximum is colored Red
    #Minimum is colored Black
    for i in range(len(lengthList)-1):
        if lengthList[i] == min(lengthList):
            canvas.itemconfig(barList[i], fill='red')
        elif lengthList[i] == max(lengthList):
            canvas.itemconfig(barList[i], fill='black')

使用 Tk 小部件创建一个窗口

window = tk.Tk()
window.title('Sorting Visualizer')
window.geometry('600x450')

#Making a Canvas within the window to display contents
canvas = tk.Canvas(window, width='600', height='400')
canvas.grid(column=0,row=0, columnspan = 50)

#Buttons
insert = tk.Button(window, text='Insertion Sort', command=insertion_sort)
select = tk.Button(window, text='Selection Sort', command=selection_sort)
bubble = tk.Button(window, text='Bubble Sort', command=bubble_sort)
shuf = tk.Button(window, text='Shuffle', command=generate)
insert.grid(column=1,row=1)
select.grid(column=2,row=1)
bubble.grid(column=3,row=1)
shuf.grid(column=0, row=1)

generate()
window.mainloop()

【问题讨论】:

标签: python for-loop tk yield


【解决方案1】:

如果您查看所有具有全局变量的函数,这意味着您的函数会更新全局变量并且不需要返回某些内容,这就是为什么在下一步调用它们时您有一个简单的yield调用以更新一些全局变量以不返回/产生一些东西

【讨论】:

  • 能否详细说明
  • 你有一个简单的yield,因为你的函数必须更新全局变量,在一个简单的 aswer 中:)
  • 在bubble_function中,当yield被移除时,气泡短动画消失,它只显示结局结果。我想知道yield在这段代码中是如何工作的
  • @VinayakKhandekar 听起来你在问yield 开始做什么?
  • 那我不明白你的问题。 Yield 一直在做它一直在做的事情。
猜你喜欢
  • 2012-12-07
  • 2016-01-02
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多