考虑以下代码:

l=[21,23,25,30,33,45,56,67,70,77--------------------]
h=35
r1=[]; r2=[]
for i in range(len(l)):
   if(l[i] < h):
      r1.append(l[i])
   else:
      r2.append(l[i])
print r1
print r2


获得的结果是:

[21, 23, 25, 30, 33]
[45, 56, 67, 70, 77----------------------]


现在我需要增加h = 35,以便当它达到46时,其输出必须为

[21, 23, 25, 30, 33,45]
[56, 67, 70, 77----------------------]


当h达到57时

[21, 23, 25, 30, 33,45,56]
[67, 70, 77-------------------------]


因此,总体而言,最终结果应显示为:

[21, 23, 25, 30, 33]
[45, 56, 67, 70, 77-----------------]

[21, 23, 25, 30, 33,45]
[56, 67, 70, 77---------------]

[21, 23, 25, 30, 33,45,56]
[67, 70, 77--------------]

[21, 23, 25, 30, 33,45,56,67]
[70, 77--------------]

[21, 23, 25, 30, 33,45,56,67,70]
[77--------------]

[21, 23, 25, 30, 33,45,56,67,70,77]
[-----------------------]


什么会在不将其作为函数参数传递的情况下在python中产生这样的结果?

最佳答案

除了jimifiki的答案外,还可以简化代码并使之具有更多的pythonic功能。

def funct(h):
    l = [21,23,25,30,33,45,56,67,70,77]
    r1=[]; r2=[]
    for x in l:
        if x < h:
           r1.append(x)
        else:
           r2.append(x)

    print r1
    print r2

for h in (35,45,55,65):
    funct(h)

关于python - 要更新变量的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18328513/

10-12 15:14