简体   繁体   中英

execute several times the same procedure in python

In my code I'm currently doing something like this:

for _ in xrange(n):
    f(x)

where f is some arbitrary function that does not return anything (ie just a None ) and x is an arbitrary input for this function

I was just wondering whether there is a proper way to do this in one line? There are a lot of functions in python like map , fold , etc that are used to operate on elements of a list, but all of them seem to consider that we are interested in what the function returns.

Doing:

[f(x) for _ in xrange(n)]

is actually working fine, but it returns a whole list of None that I don't need.

two lines is fine and expected.

You could do for _ in range(n): f(x) if you had a good reason, but you probably don't have one of those.

For me, writing something like

for i in array: f(x)

works in python 2.7 and 3

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