Python default variable for loop

I am wondering if Python has the concept of storing data in a default variable for a loop.

For example, in perl, the equivalent is as follows

foreach (@some_array) {
    print $_
}

Thanks Derek

+3
source share
4 answers

No. You should just use

for each in some_array:
    print each
+15
source

Just for fun, there is something that does just what you want. By default, it associates a loop variable with the name "_each", but you can override this with your own choice by providing it with an argument var.

import inspect

class foreach(object):
    __OBJ_NAME = '_foreach'
    __DEF_VAR = '_each'

    def __init__(self, iterable, var=__DEF_VAR):
        self.var = var
        f_locals = inspect.currentframe().f_back.f_locals
        if self.var not in f_locals:  # inital call
            self.iterable = iter(iterable)
            f_locals[self.__OBJ_NAME] = self
            f_locals[self.var] = self.iterable
        else:
            obj = f_locals[self.__OBJ_NAME]
            self.iterable = obj.each = obj.iterable

    def __nonzero__(self):
        f_locals = inspect.currentframe().f_back.f_locals
        try:
            f_locals[self.var] = self.iterable.next()
            return True
        except StopIteration:
            # finished - clean up
            del f_locals[self.var]
            del f_locals[self.__OBJ_NAME]
            return False

some_array = [10,2,4]
while foreach(some_array):
    print _each

print
while foreach("You can do (almost) anything in Python".split(), var='word'):
    print word
+2
source

Python '_' ( ). , -, , (. , Python ? Pythonic ). , , Perl , - :

some_list = [1, 2, 3]
for _ in some_list:
    print _

, , , , .

+1

All that is used in the for for syntax becomes the variable that this element stores in iteration for the rest of the loop.

for item in things:
    print item

or

for googleplexme in items:
    print googleplexme

The syntax looks like this:

for <given variable> in <iterable>:

means that if a given variable can be anything you like in your namespace, and iterable can be an iterable source.

0
source

Source: https://habr.com/ru/post/1776261/


All Articles