Is there a "foreach" function in Python 3?

When I encounter a situation, I can do it in javascript, I always think that if the foreach function is convenient. In foreach, I mean the function that is described below:

 def foreach(fn,iterable): for x in iterable: fn(x) 

they just do it on every element and do not give or return anything, I think it should be a built-in function and should be faster than writing it with pure Python, but I did not find it on the list, or it is simply called by a different name Or am I just missing a few points here?

Maybe I'm wrong because calling a function in Python is expensive, definitely not a good practice for an example. Instead of exiting the loop, the function should make a loop inside, its body looks like the one shown below, which has already been mentioned in many sentences of python code:

 def fn(*args): for x in args: dosomething 

but I thought that foreach is still welcomed on the basis of two facts:

  • In ordinary cases, people just don't care about performance
  • Once upon a time, the API did not accept an iterative object, and you cannot rewrite its source.
+112
python foreach
Aug 18 '13 at 0:14
source share
8 answers

Every appearance of "foreach" I saw (PHP, C #, ...) is basically the same as the pythons for statement.

They are more or less equivalent:

 // PHP: foreach ($array as $val) { print($val); } // C# foreach (String val in array) { console.writeline(val); } // Python for val in array: print(val) 

So yes, there is a "foreach" in python. It is called "for."

What you are describing is a map map function. This can be done using a list of concepts in python:

 names = ['tom', 'john', 'simon'] namesCapitalized = [capitalize(n) for n in names] 
+140
Aug 18 '13 at 0:33
source share

Python does not have a foreach per se. It has for loops built into the language.

 for element in iterable: operate(element) 

If you really want to, you can define your own foreach function:

 def foreach(function, iterable): for element in iterable: function(element) 

As a side note, the syntax for element in iterable comes from the ABC programming language , one of Python's influences.

+43
Aug 18 '13 at 0:18
source share

Other examples:

Python Foreach loop:

 array = ['a', 'b'] for value in array: print(value) # a # b 

Python For Loop:

 array = ['a', 'b'] for index in range(len(array)): print("index: %s | value: %s" % (index, array[index])) # index: 0 | value: a # index: 1 | value: b 
+27
Apr 26 '17 at 16:34
source share

map can be used for the situation mentioned in the question.

for example

 map(len, ['abcd','abc', 'a']) # 4 3 1 

For functions that take multiple arguments, you can specify more arguments for map:

 map(pow, [2, 3], [4,2]) # 16 9 

Returns a list in Python 2.x and an iterator in Python 3

If your function accepts several arguments and the arguments are already represented as tuples (or any iterable starting with python 2.6), you can use itertools.starmap . (which has syntax very similar to what you were looking for). Returns an iterator.

for example

 for num in starmap(pow, [(2,3), (3,2)]): print(num) 

gives us 8 and 9

+5
Aug 18 '13 at 0:38
source share

If I understood correctly, you mean that if you have a func function, you want to check each item in the list if func (item) returns true; if you go back to everyone, then do something.

You can use "everything."

For example: I want to get all primes in the range 0-10 in the list:

 from math import sqrt primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))] 
+2
Jun 02 '17 at 9:09 on
source share

This makes foreach in Python 3

 test = [0,1,2,3,4,5,6,7,8,"test"] for fetch in test: print(fetch) 
+2
Apr 16 '18 at 11:07
source share

Have a look in this article . The numpy numpy iterator object introduced in NumPy 1.6 provides many flexible ways to systematically use all elements of one or more arrays.

Example:

 import random import numpy as np ptrs = np.int32([[0, 0], [400, 0], [0, 400], [400, 400]]) for ptr in np.nditer(ptrs, op_flags=['readwrite']): # apply random shift on 1 for each element of the matrix ptr += random.choice([-1, 1]) print(ptrs) d:\>python nditer.py [[ -1 1] [399 -1] [ 1 399] [399 401]] 
+1
Jun 09 '17 at 11:49 on
source share

If you're just looking for a shorter syntax, you can put the for loop on one line:

 array = ['a', 'b'] for value in array: print(value) 

Just separate the extra operators with a semicolon.

 array = ['a', 'b'] for value in array: print(value); print('hello') 

This may not be appropriate for your local style guide, but it may make sense to do so when you play in the console.

+1
Jun 17 '19 at 21:44
source share



All Articles