Why are arbitrary target expressions allowed in for-loops?

后端 未结 4 1447
臣服心动
臣服心动 2020-12-12 20:14

I accidentally wrote some code like this:

foo = [42]
k = {\'c\': \'d\'}

for k[\'z\'] in foo:  # Huh??
    print k

But to my surprise, this

4条回答
  •  忘掉有多难
    2020-12-12 20:59

    Is there any situation in which this is actually useful?

    Indeed. Ever wanted to get rid of itertools.combinations?

    def combinations (pool, repeat):        
        def combinations_recurse (acc, pool, index = 0):
            if index < len(acc):
                for acc[index] in pool:
                    yield from combinations_recurse(acc, pool, index + 1)
            else:
                yield acc
    
        yield from combinations_recurse([pool[0]] * repeat, pool)
    
    for comb in combinations([0, 1], 3):
        print(comb)
    

提交回复
热议问题