使用class-object附加列表会覆盖所有以前的列表元素

时间:2018-02-14 12:24:41

标签: python list append

我花了很多时间试图弄清楚问题是什么,并且已经尝试了几种我在其他问题中找到的方法,但它仍然不起作用。我想将所有类对象存储在列表" houselist"但不是附加列表,它只给了我几次相同的条目。我想这是某种参考问题,但我无法弄明白。这是代码:

# Definition of the house object class
class House_object():
    def __init__(self, price, surfaceArea, rent, tNumber, adress, monthlyCost, areaCost):
        self.price = price
        self.surfaceArea = surfaceArea
        self.rent = rent
        self.tNumber = tNumber
        self.adress = adress
        self.monthlyCost = monthlyCost
        self.areaCost = areaCost

#reading the file
f = open("bfil.txt", "r")
content = f.read()
splitlist = content.split("\n")
f.close()

num_lines = sum(1 for line in open('bfil.txt'))

#creating the list "houselist" and adding the class instances to it
houselist = []
for i in range(0, num_lines, 5):
    price = int(splitlist[0 + i])
    surfaceArea = int(splitlist[1 + i])
    rent = int(splitlist[2 + i])
    tNumber = splitlist[3 + i]
    adress = splitlist[4 + i]
    monthlyCost = int(rent + (((price - dPayment) * (bankRate / 100) * (1 - (intrestDeduct / 100))) / 12))
    areaCost = int(price / rent)
    bostad = House_object(price, surfaceArea, rent, tNumber, adress, monthlyCost, areaCost)

    houselist.append(bostad) # I think here might be the problem??

    for element in houselist:
        print("this is the list during the loop: " + bostad.adress)

最后的打印命令给出了以下内容:

this is the list during the loop: Streetgatan 1
this is the list during the loop: KTHstreet 7
this is the list during the loop: KTHstreet 7
this is the list during the loop: weststreet 66
this is the list during the loop: weststreet 66
this is the list during the loop: weststreet 66
this is the list during the loop: Delilstreet 57
this is the list during the loop: Delilstreet 57
this is the list during the loop: Delilstreet 57
this is the list during the loop: Delilstreet 57

因此,对于每个循环,python会覆盖我的列表并添加新实例,但也会替换已存在的实例。 我原以为这个:

this is the list during the loop: Streetgatan 1
this is the list during the loop: Streetgatan 1
this is the list during the loop: KTHstreet 7
this is the list during the loop: Streetgatan 1
this is the list during the loop: KTHstreet 7
this is the list during the loop: weststreet 66
this is the list during the loop: Streetgatan 1
this is the list during the loop: KTHstreet 7
this is the list during the loop: weststreet 66
this is the list during the loop: Delilstreet 57

我试过了两个     houselist.append(bostad) 和     houselist = houselist [:] + bostad

我在其他一些帖子中读到了这种可能性,所以我尝试了这个,但仍然给了我相同的结果。我非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

查看你的代码,你不打印正确的东西:

houselist.append(bostad) # I think here might be the problem??

for element in houselist:
    print("this is the list during the loop: " + bostad.adress)

您正在打印bostad.adress,因此您只是打印上一个附加项目的地址而不是:

for element in houselist:
    print("this is the list during the loop: " + element.adress)