Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, I'm repeating myself a lot when it comes to for loops and there must be a better way

Lets say I have three lists and I need to iterate through them and do some stuff to the contents.

The three lists are streaks_0, streaks_1, and streaks_2. For each list, I need to use different values specific to each list. For example, streak_0_num0s will not work in the streaks_1 for loop.

Is there a way to make these three for loops into one or at least a way to clean this up?

for number in streaks_0:
    if number == 0:
        streak_0_num0s += 1
    elif number != 0:
        streak_0_sum += number
streak_0_average = (streak_0_sum / (len(streaks_0) - streak_0_num0s))

for number in streaks_1:
    if number == 0:
        streak_1_num0s += 1
    elif number != 0:
        streak_1_sum += number
streak_1_average = (streak_1_sum / (len(streaks_1) - streak_1_num0s))

for number in streaks_2:
    if number == 0:
        streak_2_num0s += 1
    elif number != 0:
        streak_2_sum += number
streak_2_average = (streak_2_sum / (len(streaks_2) - streak_2_num0s))
like image 825
Ari Madian Avatar asked May 31 '17 19:05

Ari Madian


People also ask

How do you stop a for loop repeating in Python?

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

How do you stop a loop from repeating?

The only way to exit a repeat loop is to call break.

How do you repeat a loop multiple times in Python?

You can do the same type of for loop if you want to loop over every character in a string. To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.

How do you stop an infinite loop in Python?

You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.


1 Answers

Why not use a function?

def get_average(streaks):
    streak_0_num0s = 0
    streak_0_sum = 0

    for number in streaks:
        if number == 0:
            streak_0_num0s += 1
        elif number != 0:
            streak_0_sum += number
    streak_0_average = (streak_0_sum / (len(streaks) - streak_0_num0s))
    print(streak_0_average)

get_average(streaks01)
get_average(streaks02)
get_average(streaks03)
like image 64
CodeLikeBeaker Avatar answered Oct 22 '22 02:10

CodeLikeBeaker