小编Bro*_*bat的帖子

为什么Python的itertools.cycle需要创建iterable的副本?

Python的itertools.cycle()文档给出了伪代码实现:

def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element
Run Code Online (Sandbox Code Playgroud)

下面,它指出:"注意,该工具包的这个成员可能需要大量的辅助存储(取决于可迭代的长度)."

我基本上是沿着这条路走,除了我这样做,这不需要创建iterable的副本:

def loop(iterable):
    it = iterable.__iter__()

    while True:
        try:
            yield it.next()
        except StopIteration:
            it = iterable.__iter__()
            yield it.next()

x = {1, 2, 3}

hard_limit = 6
for i in loop(x):
    if hard_limit <= 0:
        break

    print i
    hard_limit -= 1
Run Code Online (Sandbox Code Playgroud)

打印:

1 …
Run Code Online (Sandbox Code Playgroud)

python iterator cycle python-itertools

9
推荐指数
1
解决办法
1471
查看次数

Python 3.2.1:exec('x = y()')在玩具示例中设置一个值,但不在完整代码中设置

我正在使用exec()语句设置一个值,如下所示:

foo = 3
def return_4():
    return 4
instruction = 'foo = return_4()'
exec(instruction)                     # <---- WHERE THE MAGIC HAPPENS
print(foo)
Run Code Online (Sandbox Code Playgroud)

正如我所料,这是4.

我的程序有操作Rubik的立方体的操作.在这个精简版中,我会做四件事:

  1. 我将实例化一个立方体,填充一个面(缩写为"前左上"和"前右下"等).

  2. 我将有一个旋转前脸的功能.

  3. 我将有一个'解释器'函数,它接受一个多维数据集和一个指令列表,并将这些指令应用于多维数据集,返回修改后的多维数据集.这是我使用'exec'的地方(以及我认为破损发生的地方).

  4. 最后,我将在部分立方体上运行解释器,并指示旋转面部一次.

+

my_cube = [['FTL', 'FTM', 'FTR',
            'FML', 'FMM', 'FMR',
            'FBL', 'FBM', 'FBR'],
            [],[],[],[],[]] # other faces specified in actual code

def rotate_front(cube):
    front = cube[0]
    new_front = [front[6],front[3],front[0],
                 front[7],front[4],front[1],
                 front[8],front[5],front[2]]
    # ...
    ret_cube = cube
    ret_cube[0] = new_front
    # pdb says we are returning a correctly rotated cube,
    # and calling this directly …
Run Code Online (Sandbox Code Playgroud)

python exec rubiks-cube

2
推荐指数
1
解决办法
977
查看次数

标签 统计

python ×2

cycle ×1

exec ×1

iterator ×1

python-itertools ×1

rubiks-cube ×1