简体   繁体   中英

How to write a enumerate loop

I was wondering if it is possible to run an enumerate loop as as we can see below

int_term = [scipy.quad(t_x,x0,i)[0] for i in enumerate(x_vals)]

or do we have to write it this way

for i in enumerate(x_vals)

Hopefully this clarifies what exactly enumerate does:

>>> list(enumerate('abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]

It just turns your list into a list of a pairs where each of your elements is joined with the index ie a with 0, b with 1 and c with 2.

That's not exactly true because it is an iterator rather than an actual list - so it provides you with values lazily when you wrap another iterator.

Looping over it is therefore the same as any other lists except usually it is done the following way:

for i, x in enumerate(xs)

You could still use:

for i in enumerate(xs)

but then just know that i is going to be a tuple with some int, and some object from xs .

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