如何正确使用def中的for循环?

时间:2019-12-21 09:33:01

标签: python function for-loop

def kolas(lst, n):
    for i in range(0, len(lst)):
        e = []
        x = lst[i] % n
        e.append(x)
    return x

我注意到for循环在def()中不起作用- i 仅由列表的第一个值分配。是否存在像for循环这样的函数会影响def()?

2 个答案:

答案 0 :(得分:1)

您可以为此使用foreach交互

def kolas(lst, n):
    e = [] # Notice that we don't want to create it each time, only the first time
    for i in lst: # for each element in lst
        x = i % n # i now equals to the lst value
        e.append(x) # adding it into e
    return e # Returning e

答案 1 :(得分:-1)

对于ie的每次迭代都会重新分配到一个空列表。将e = []移动到for循环之前。