筛选列表而不创建新列表?

时间:2019-03-19 12:24:08

标签: python

因此,我正在一个有对象列表的项目中工作。我想根据对象属性过滤列表,但是由于此列表在我的代码的许多其他地方都使用过,因此我无法创建新列表,因为它将在我的代码的其他地方造成问题。

我尝试使用此:

individuals = list(filter(lambda x: x.waterstore > 0, individuals))

但是它给我“ UnboundLocalError:赋值之前引用的局部变量'individuals'。”

这里是发生问题的代码。

def day(numberOfDays):
   days = 0
   while days < numberOfDays:
       print(str(days) + " days")
       child = randint(1,100)
       if child > 95:
           IndividualGenerator(randint(1,2))
       SeekWaterHole(individuals, lakes)
       rain(lakes)
       DrinkWater(individuals, lakes)
       for r in range(len(individuals)):
           individuals[r].waterstore -= 1
       individuals = list(filter(lambda x: x.waterstore > 0,individuals))
       individualTotalWater = []
       for i in individuals:
           individualTotalWater.append(i.waterstore)
       AmountWater = lakes[0].water
       Logg = [AmountWater, sum(individualTotalWater), len(individuals)]
       with open("NewCSVTestFile.csv", "a") as f:
               openfile = csv.writer(f, delimiter=",")
               openfile.writerow(Logg)
       print("logg " + str(Logg))
       print()
       days += 1

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

  

“ UnboundLocalError:分配前引用了本地变量'individuals'”。

您对individuals的首次引用出现在这里:

SeekWaterHole(individuals, lakes)

,但尚未在函数中定义,也未作为函数的输入给出。因此,python不知道它引用了什么。

答案 1 :(得分:0)

您可以在错误行之前将个人[]添加为空列表,或者您可以将个人初始化为全局。

from random import randint
def day(numberOfDays):
individuals=''
days = 0
while days < numberOfDays:
    print(str(days) + " days")
    child = randint(1,100)
    #if child > 95:
        #IndividualGenerator(randint(1,2))
    individuals=[]//initialize the list before using it
    #SeekWaterHole(individuals, lakes)
    #rain(lakes)
    #DrinkWater(individuals, lakes)
    for r in range(len(individuals)):
        individuals[r].waterstore -= 1
    individuals = list(filter(lambda x: x.waterstore > 0,individuals))
    individualTotalWater = []
    for i in individuals:
        individualTotalWater.append(i.waterstore)
    #AmountWater = lakes[0].water
    #Logg = [AmountWater, sum(individualTotalWater), len(individuals)]
    #with open("NewCSVTestFile.csv", "a") as f:
    #        openfile = csv.writer(f, delimiter=",")
    #        openfile.writerow(Logg)
    #print("logg " + str(Logg))
    print()
    days += 1
day(10)