简体   繁体   English

我怎么能洗牌 python 无限生成器

[英]How could I shuffle python infinite generator

I have an object which I make it to be an generator:我有一个对象,我使它成为一个生成器:

class obj(object):
     def __init__():
         pass
     def __iter__():
         a = list(range(10))
         shuffle(a)
         for i in range(len(a)):
             yield a[i]
     .....

It can be seen that there is a shuffle operation when the generator is created.可以看出在创建生成器的时候有一个shuffle操作。 When I use itertools.cycle , this generator can works infinitely, but no shuffle operator will be done except the first time.当我使用itertools.cycle ,这个生成器可以无限工作,但除了第一次之外不会执行任何 shuffle 运算符。 How could I create an infinite generator behaves like itertools.cycle but can still implement shuffle each cycle ?我怎么能创建一个无限生成器,它的行为类似于itertools.cycle但仍然可以实现每个周期的 shuffle ?

First: don't call your generator __iter__ as that is reserved for making your object instances iterable (without a call to a specific method).首先:不要调用您的生成器__iter__因为它是为使您的对象实例可迭代而保留的(无需调用特定方法)。

For generating an infinite list of values, you would not really need to shuffle.为了生成一个无限的值列表,你真的不需要洗牌。 Instead just pick a random value from the list each time.而是每次从列表中随机选择一个值。 Add logic if you want to prevent the same value to be picked too soon after the previous same pick, although the more you control that, the less random it becomes.如果您想防止在上一次相同的选择后过早地选择相同的值,请添加逻辑,尽管您控制得越多,它的随机性就越小。

import random

class obj(object):
     def __init__(self):
         pass
     def items(self):  # Generator
         a = list(range(10))
         while True:
             yield random.choice(a)

If your list a really is just a sequence from 0 to 9 (included), then do:如果您的列表a真的只是一个从 0 到 9(包括在内)的序列,那么请执行以下操作:

     def items(self):  # Generator
         while True:
             yield random.randint(0, 10)

If you really want all list values to have been produced before restarting, then please be aware that the last pick of the first batch might be the same as the first pick from the second batch.如果您真的希望在重新启动之前生成所有列表值,那么请注意第一批的最后一次选择可能与第二批中的第一次选择相同。 Anyway, that would look like this:无论如何,这看起来像这样:

     def items(self):  # Generator
         a = list(range(10))
         while True:
             shuffle(a)
             yield from a
from random import shuffle

class my_generator():
    n = 10
    def __init__(self):
        pass

    def __iter__(self):
        a = list(range(self.n))
        shuffle(a)
        for i in range(len(a)):
            yield a[i]

    def get(self):
        my_list = []
        for i in range(self.n):
            my_list.append(self.__iter__().__next__())

        return my_list


obj =my_generator()
my_list = obj.get()
print(my_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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