简体   繁体   English

python-内部循环不覆盖全局变量

[英]python - inner loop not overriding global variable

this is one of the dumbest questions ever! 这是有史以来最愚蠢的问题之一!

I have a for loop: 我有一个for循环:

inner_step = 0
for i, v in enumerate(['a','b'], start=1 if inner_step == 0 else (inner_step+1)):
     print str(i) + ': ' + v
     for k, m in enumerate(['1','2'], start=i+1):
         print str(k) + ': ' + m
         inner_step = k

I hoped for 我希望

1: a
2: 1
3: 2
4: b
5: 1
6: 2

but I am getting 但我越来越

1: a
2: 1
3: 2
2: b
3: 1
4: 2

obviously, inner_step is not being overridden by inner loop. 显然, inner_step不会被内部循环覆盖。 what am I doing wrong? 我究竟做错了什么?

You can use itertools.count to keep track of the count 您可以使用itertools.count来跟踪计数

from itertools import count

step = count(1)
for v in ['a', 'b']:
    print(str(next(step)) + ': ' + v)
    for m in ['1', '2']:
        print(str(next(step)) + ': ' + m)

1: a
2: 1
3: 2
4: b
5: 1
6: 2

A first step of simplification could be this (although still far away from a pythonic solution): 简化的第一步可能是这样(尽管距离pythonic解决方案还很远):

c = 1
for v in ['a','b']:
    print str(c) + ': ' + v
    c += 1
    for m in ['1','2']:
        print str(c) + ': ' + m
        c += 1

Your outer loop iterator is not updated after each iteration. 您的外循环迭代器不会在每次迭代后更新。 The enumerate() object is created just once . enumerate()对象仅创建一次

Keep an explicit counter to be updated across the loops: 保留一个明确的计数器,以在循环中进行更新:

step = 0
for v in ['a','b']:
     step += 1
     print '{}: {}'.format(step, v)
     for m in['1','2']:
         step += 1
         print '{}: {}'.format(step, m)

or use calculate the numbers from the enumerate numbers: 或使用从枚举数字计算数字:

for outer, v in enumerate(['a','b']):
     print '{}: {}'.format(outer * 3 + 1, v)
     for inner, m in enumerate(['1','2']):
         print '{}: {}'.format(outer * 3 + 2 + inner, m)

Both produce the desired output: 两者都产生所需的输出:

>>> step = 0
>>> for v in ['a','b']:
...      step += 1
...      print '{}: {}'.format(step, v)
...      for m in['1','2']:
...          step += 1
...          print '{}: {}'.format(step, m)
... 
1: a
2: 1
3: 2
4: b
5: 1
6: 2
>>> for outer, v in enumerate(['a','b']):
...      print '{}: {}'.format(outer * 3 + 1, v)
...      for inner, m in enumerate(['1','2']):
...          print '{}: {}'.format(outer * 3 + 2 + inner, m)
... 
1: a
2: 1
3: 2
4: b
5: 1
6: 2

This seems a good application for a generator. 对于发电机来说,这似乎是一个很好的应用。 Here the sequence generation code is separated from the enumeration and printing code which makes it possible to reuse the sequence generation code elsewhere. 此处,序列生成代码与枚举和打印代码分开,这使得可以在其他地方重用序列生成代码。

def expand(seq1, seq2):
    for outer in seq1:
        yield outer
        for inner in seq2:
            yield inner

for i, v in enumerate(expand(['a','b'], ['1','2']), start=1):
    print("{}: {}".format(i, v))

1: a
2: 1
3: 2
4: b
5: 1
6: 2

# or just pass the items to expand() in strings
for i, v in enumerate(expand('abc', '123'), start=1):
    print("{}: {}".format(i, v))

1: a
2: 1
3: 2
4: 3
5: b
6: 1
7: 2
8: 3
9: c
10: 1
11: 2
12: 3

expand() could also be implemented as a normal function that constructs and returns a local list of items from the sequences, however, this generator function is cleaner (no local list required) and more efficient for expanding long sequences. expand()也可以实现为普通函数,该函数构造并返回序列中的项的本地列表,但是,此生成器函数更简洁(不需要本地列表),并且对于扩展长序列更有效。

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

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