用classobject追加列表将覆盖以前的所有列表元素

2024-10-02 22:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了相当长的时间试图找出问题是什么,并已经尝试了几种方法,我发现在其他问题,但仍然没有工作。我想把我所有的类对象都存储在列表“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)

最后的print命令提供了以下信息:

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

我两个都试过了 房屋列表.append(博斯塔德) 和 房屋列表=房屋列表[:]+博斯塔德

我在其他一些帖子中读到了这种可能性,所以我尝试了这个方法,但仍然得到了相同的结果。我非常感谢你的帮助!你知道吗


Tags: theselfloop列表isthispricelist
1条回答
网友
1楼 · 发布于 2024-10-02 22:35:57

查看您的代码,您没有打印正确的内容:

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)

相关问题 更多 >