简体   繁体   中英

is there some way execute every element simply?

normal way:

for x in myList:
    myFunc(x)

you must use a variable x

use

map(myFunc,myList)

and in fact you must use this to make above work

list(map(myFunc,myList))

that would build a list,i don't need to build a list

maybe some one would suggest me doing this

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

that is another topic

is there something like this?

every(func,myList)

The 'normal way' is definitely the best way, although itertools does offer the consume recipe for whatever reason you might 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 could be used like:

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

This function performs the fastest as it avoids python for loop overhead by using functions which run on the C side.

AFAIK there is no 'foreach' shortcut in the standard library, but such a thing is very easy to implement:

def every(fun, iterable):
    for i in iterable:
        fun(i)

If you just want myList to be modified to contain myFunc(x) for all x in myList then you could try a list comprehension which also requires a variable, but doesn't let the variable leak out of the scope of the comprehension:

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

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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