Is there any way to just execute each element?

normal way:

for x in myList: myFunc(x) 

you must use the variable x

use

 map(myFunc,myList) 

and in fact you should use this to do the above job

 list(map(myFunc,myList)) 

which will create a list, I do not need to create a list

Can someone suggest me to do this

 def func(l): for x in l: .... 

this is another topic

is there something similar?

 every(func,myList) 
+4
source share
3 answers

The "normal way" is by far the best way, although itertools offers a recipe for consumption for whatever reason you may need it:

 import collections from itertools import islice def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty slice starting at position n next(islice(iterator, n, n), None) 

This can be used as:

 consume(imap(func, my_list), None) # On python 3 use map 

This function does the fastest work since it avoids python for loop overhead by using functions performed on the C side.

+6
source

AFAIK there is no "foreach" label in the standard library, but it is very easy to implement:

 def every(fun, iterable): for i in iterable: fun(i) 
+3
source

If you want myList be modified to contain myFunc(x) for all x in myList , then you can try list comprehension, which also requires a variable, but does not allow the variable to go out of scope:

 myList = [myFunc(x) for x in myList] 

Hope that helps

0
source

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


All Articles