将函数应用于Python中的多个列表

时间:2013-11-14 22:51:32

标签: python list function

我将类的前4个测验的分数设置为单独的数组。我创建了一个从列表中删除所有零的函数。如何应用该函数并在最后获得四个不同的列表,而不是零?

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

3 个答案:

答案 0 :(得分:1)

您可以返回包含所需列表的列表:

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

答案 1 :(得分:1)

使用两个列表推导更容易完成:

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

答案 2 :(得分:0)

可选地,

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

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