locoboy
locoboy

Reputation: 38960

What does this code segment in python mean?

I'm trying to understand what is going on here, specifically how curids is getting set:

 for idx in xrange(0, int(math.ceil(float(len(mids))/chunk))):
            curids = mids[int(idx*chunk):int((idx*chunk)+chunk)]

I'm not sure what the syntax for mids[int(idx*chunk):int((idx*chunk)+chunk)] is trying to do.

Upvotes: 2

Views: 1826

Answers (4)

NPE
NPE

Reputation: 500893

It extracts blocks of mids into curids, where each block consists of chunk elements.

If you change the loop to print out the values of int(idx*chunk) and int((idx*chunk)+chunk)], you'll see that for yourself.

For example, if len(mids)==50 and chunk==12, the indices that would get printed are:

0 12
12 24
24 36
36 48
48 60

These are the starting and ending indices of each slice of mids (the start index is inclusive and the end index is not).

Note that the last value is allowed to go above len(mids), but that's not a problem given how Python slicing works (it'll just slice to the end of mids).

Upvotes: 2

Tincu Gabi
Tincu Gabi

Reputation: 11

So then, as far as i can see the loop splits the mids list into chunks the size of chunk and curids is being attribuited those chunks. So for example if mids was a 20 values list and chunk was 4, curids would be attribuited the values mids[0:4],mids[4:8],..mids[16:20] , basically splitting the list in 5

Upvotes: 0

Jon
Jon

Reputation: 10503

The code mids[int(idx*chunk):int((idx*chunk)+chunk)] is getting a subset of the list. The resulting int to the left of the : is the start position in the list, the int to the right is the end position. So the format is: list[start:end]

Upvotes: 0

Narendra Yadala
Narendra Yadala

Reputation: 9664

It extracts chunk number of elements from mids starting at idx*chunk and places them into curids.

Upvotes: 0

Related Questions