Get Loop Count Inside a For-Loop

Get loop count inside a for-loop

The pythonic way is to use enumerate:

for idx, item in enumerate(my_list):

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

count for loop iteration and do something

Do you mean to run some code and if it fails, retry, but max. 5 times? You can do it this way:

for (int i = 5; i > 0; i--) {
try {
doSomething();
break; // Break if successful.
} catch (Exception e) {
// TODO Print the exception, etc.
Thread.Sleep(1000); // Delay the next iteration.

// Optional: Rethrow if it is the last iteration.
if (i == 0) {
throw e;
}
}
}

You can replace the doSomething(); line with the actual code or call a (private) method that performs that operation. The latter is usually preferred, since you separate the looping construct from the actual code.

Note that the break is placed after the work. Therefore, if the doSomething() fails, it skips the break; line and goes directly to the catch (and then to the next iteration). If it succeeds, it breaks out from the loop.

using readlines() and count() in a for loop?

Let's dissect the loop:

for line in f.readlines():
c += line.count(S)

f is a file descriptor of your open file.

readlines is a generator, a function sort of thing that returns the lines of the file. If you think of it as a list of strings, each of which is a line of the file, you'll be close enough to understand the loop operation.

Thus, the statement for line in f.readlines(): iterates the variable line through the file contents; on each loop iteration, line will be the appropriate string value, the next line of the file.

Therefore, line.count(S) returns the quantity of times the target string S appears in that line of the file. The increment c += adds that to your counter.

Does that make things clear enough?


BTW, please learn to use descriptive variable names. One-letter names with mixed upper- and lower-case are a bad habit in the long run.

How to get count of for loop and store it into dictionary which is inside for loop

I don't have idea of how to get perfect count of for loop inside condition

To get the perfect count of the for loop, I recommend using enumerate() built-in function within Python.Example:

>>> for count, value in enumerate(values):
... print(count, value)
...
0 a
1 b
2 c

This will allow you to keep a perfect count at all times. You can start at count 0 or use +1 to start from 1.

Your desired dictionary is a dictionary within the dictionary. To do this create another dictionary (call b) and use this to assign the values within the forloop. Once all the values are assigned use the other dictionary (call a) and set the key value of preshift in a to b, e.g. a["preshift"] = b. This will make it the way you want.

I am also confused on how you are using the variable pre_shift_count in this case. An easy way around this is to use the b dictionary of type int. You would initialize with defaultdict(int) in python and then in each case increment the value by 1 e.g., b[key]+=1

Iteration counter for double loops

The Double-for-loop (a.k.a. Nested loops).

# Set count to 0 before loop starts
count = 0

for i in range(5):
for j in range(5):
# solved mysterious formula (short hand 'count = count + 1')
count += 1
# displaying count after loop
print(count)

Expanding on the formula count = count + 1, this sets count to be equal itself + 1:

count = count + 1

How can I create a for-loop to count the number of values within a vector that fall between a set boundary?

Are you looking for something like this? Your code doesn't work because your syntax is incorrect.

vec <- c(1, 3, 4, 5, 8, 9, 10, 54) #Input vector

countvalswithin <- vector() #Empty vector that will store counts of values within bounds

#For loop to cycle through values stored in input vector
for(i in 1:length(vec)){
currval <- vec[i] #Take current value
lbound <- (currval - 3) #Calculate lower bound w.r.t. this value
ubound <- (currval + 3) #Calculate upper bound w.r.t. this value

#Create vector containing all values from source vector except current value
#This will be used for comparison against current value to find values within bounds.
othervals <- subset(vec, vec != currval)

currcount <- 1 #Set to 0 to exclude self; count(er) of values within bounds of current value

#For loop to cycle through all other values (excluding current value) to find values within bounds of current value
for(j in 1:length(othervals)){

#If statement to evaluate whether compared value is within bounds of current value; if it is, counter updates by 1
if(othervals[j] > lbound & othervals[j] <= ubound){
currcount <- currcount + 1
}

}

countvalswithin[i] <- currcount #Append count for current value to a vector

}

df <- data.frame(vec, countvalswithin) #Input vector and respective counts as a dataframe

df

# vec countvalswithin
# 1 1 3
# 2 3 4
# 3 4 3
# 4 5 4
# 5 8 3
# 6 9 3
# 7 10 3
# 8 54 1

Edit: added comments to the code explaining what it does.

How to access the iteration count in a for-loop inside a conditional if-then statement in R?

There you go sir

myDF1 <-
data.frame(
Name = c("R","R","X","X","X","X","X","X"),
Group = c(0,0,0,1,1,0,0,0)
)

nCode <- myDF1 %>%
group_by(Name) %>%
mutate(nmCnt = row_number()) %>%
ungroup() %>%
mutate(seqBase = ifelse(Group == 0 | Group != lag(Group), nmCnt,0)) %>%
mutate(seqBase = na_if(seqBase, 0)) %>%
group_by(Name) %>%
fill(seqBase) %>%
mutate(seqBase = match(seqBase, unique(seqBase))) %>%
ungroup %>%
mutate(grpRnk = ifelse(Group > 0, sapply(1:n(), function(x) sum(Name[1:x]==Name[x] & Group[1:x] == Group[x])),0))

library(magrittr)
nCode %<>% mutate(
contact_col=as.numeric(
paste0(seqBase,".",grpRnk)
)
)

# %<>% is just a regular pipe with a fancy way to asign to variable (instead of `<-`)

Adding a counter to a loop

You basically had it. You just need to a) initialize the counter before the loop, b) use & instead of and in your if condition, c) actually add 1 to the counter. Since adding 0 is the same as doing nothing, you don't have to worry about the "else".

counter = 0
for (blah in your_loop_definition) {
... loop code ...
if(hours$week1 > 1 & hours$week1 < 48) {
counter = counter + 1
}
... more loop code ...
}


Related Topics



Leave a reply



Submit