python利用yield生成可迭代对象,并对其进行排序

可迭代对象的生成器yield,很多人对其都模棱两可。

在一个函数中,如果使用了yield,即使包含return,它也是可迭代的。而yield其实就是return

yield和迭代器一样包含__next__()方法,通过这个方法就可以使用它。

在方法运行到yield时,可以对当前函数的运行状态做出一个记录,将yield右边的值作为返回值,其返回给函数并交回控制权,当再次调用__next__()时,会直接从yield下面的语句运行,这一点类似于嵌入式中的中断系统,不同的是中断系统是CPU自动控制的,而yield语句是可以人为手动控制,也可以自动控制。

 

所以,生成器yiled就相当于,一个方法可以被多次执行,并且记录,产生一个可迭代的内容,我们可以通过遍历这个可迭代的内容来使用它,也可以通过next()方法使用。

 

yield将其下面的程序暂时封存起来,next调用时再执行,还有一个好处是可以避免循环卡死,调试使用时可控性高

 

下面是一些简单测试的代码:

import random

"""
This class can make a range iterable container
arguments : number of elements ,start number, stop number

"""


class Rand_Iter(object):
    def __init__(self, num, start, stop):
        self.num = num
        self.start = start
        self.stop = stop

    def get_iter(self):
        while self.num > 0:
            rand = random.randint(self.start, self.stop)
            yield rand
            self.num -= 1


"""
this class can sort
a iterable container and will return a sorted list

"""


class IterList_Sort(object):
    def __init__(self, iter=None):
        self.iter = iter
        self.list = []
        if iter is not None:
            for val in self.iter:
                self.list.append(val)

    # alter iterable container to a list
    def add_elements(self, add_list):
        for elem in add_list:
            self.list.append(elem)

    # sort algorithm with a order argument
    def sort_fuc(self, order):
        list = self.list
        bool = lambda x, y: True if x > y else False
        for i in range(0, len(list)):
            for j in range(i, len(list)):
                if order == 'ascend':
                    if bool(list[i], list[j]):
                        list[i], list[j] = list[j], list[i]
                elif order == 'descend':
                    if not bool(list[i], list[j]):
                        list[i], list[j] = list[j], list[i]
        return list

    # get a sorted list(ascend)
    def ascend_sort(self):
        return self.sort_fuc('ascend')

    # get a sorted list(descend)
    def descend_sort(self):
        return self.sort_fuc('descend')

    # get number of the elem in the iterable containers
    def get_length(self):
        print("the iterable container length is ", len(self.list))
        return len(self.list)

    def view_list(self):
        print("The Original List:")
        print(self.list)
        print("The Ascend List:")
        print(self.ascend_sort())
        print("The Descend List:")
        print(self.descend_sort())


if __name__ == "__main__":
    list = IterList_Sort()
    list.view_list()
    list.add_elements([5,2,1,3,4])
    list.view_list()
    list.get_length()
    list.add_elements(Rand_Iter(10, 1, 100).get_iter())
    list.view_list()

运行结果:

The Original List:
[]
The Ascend List:
[]
The Descend List:
[]
The Original List:
[5, 2, 1, 3, 4]
The Ascend List:
[1, 2, 3, 4, 5]
The Descend List:
[5, 4, 3, 2, 1]
the iterable container length is  5
The Original List:
[5, 4, 3, 2, 1, 46, 56, 98, 33, 69, 97, 56, 21, 20, 1]
The Ascend List:
[1, 1, 2, 3, 4, 5, 20, 21, 33, 46, 56, 56, 69, 97, 98]
The Descend List:
[98, 97, 69, 56, 56, 46, 33, 21, 20, 5, 4, 3, 2, 1, 1]

Process finished with exit code 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章