Shankar Kumar
Shankar Kumar

Reputation: 2357

Applying a function to multiple lists in Python

I have scores for the first 4 quizzes of a class set as separate arrays. I made a function that removes all zeros from the lists. How do I apply the function and obtain four different lists at the end, without the zeros?

def main():
    print remove_zeros([57,0,36,29,38,31,33,0,42,0,52,28,0,50,26,97,80,63,8,36,33,39,12,36,12,59,75,61,57,39,18,9,19,35,75,5,18,0,56,0,24,0,9],
                       [83,0,64,45,66,82,52,0,43,0,53,49,43,82,44,74,74,58,52,52,60,18,24,34,19,42,72,65,79,99,75,24,35,70,74,43,55,0,82,0,34,0,22],
                       [69,0,38,16,16,16,55,0,28,0,44.5,31,0,33,52,75,46,33,36,0,49,34.5,35,79.5,13,27,31,52,40.5,64.5,15,0,31,47,26,0,36,0,68,0,64.5,0,20],
                       [86,0,95,74,90,53,32,0,79,0,38,63,0,42,61,0,0,70,62,78,0,60,47,89,75,62,84,62,71,80,73,0,31,25,74,0,77,0,90,0,78,0,25])

def remove_zeros(*all_quizzes):
    for each_quiz in all_quizzes:
        updated_quiz_list = []
        for number in each_quiz:
            if number != 0:
                updated_quiz_list.append(number)
    return updated_quiz_list

Upvotes: 2

Views: 576

Answers (3)

C.B.
C.B.

Reputation: 8346

alternatively,

>>> mylist = [[0,1,2],[0,1,2]]
>>> def notzero(x):
        return x!=0

>>> map(lambda x : filter(notzero,x),mylist)
[[1, 2], [1, 2]]

Upvotes: 0

David Robinson
David Robinson

Reputation: 78650

This could more easily be done using two list comprehensions:

def remove_zeros(*all_quizzes):
    return [[n for n in q if n != 0] for q in all_quizzes]

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122536

You can return a list with the desired lists:

def remove_zeros(*all_quizzes):
    result = []
    for each_quiz in all_quizzes:
        updated_quiz_list = []
        for number in each_quiz:
            if number != 0:
                updated_quiz_list.append(number)
        result.append(updated_quiz_list)
    return result

Upvotes: 1

Related Questions