insert a list into a list of objects
本问题已经有最佳答案,请猛点这里访问。
在Python中,我有一个类,它包含一个作为其成员之一的列表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class fan_details: name ="" previous_addresses = [] age = 0 fans = [] x.name ="Joe Blow" x.previous_address.append("4, seaview rd") x.age = 42; fans.append(x) x.previous_address.pop(0) x.name ="Jimmy Flag" x.previous_address.append("21, Main Street") x.age = 33; fans.append(x) print fans[0].previous_address print fans[1].previous_address |
最后两份打印声明将打印出"21,大街"。append()与fans[0]类似于c中的指针。上一个地址与fans[1]相同。上一个地址。
有没有办法留住粉丝[0],以前的地址是"4,Seaview Rd"?
请容忍我,因为我是Python中的一个笨蛋。
事先谢谢。
有几个问题:
固定码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class fan_details: #you need to initialize and define the object: def __init__(self, name="", previous_address = None, age = 0): self.name = name if previous_address is None: self.previous_addresses = [] else: self.previous_addresses = [previous_address] self.age = age fans = [] x = fan_details() x.name ="Joe Blow" x.previous_addresses.append("4, seaview rd") x.age = 42; fans.append(x) #a python object is mutable!!! This means that"x" and fans[0] point to the same #python object. Lets create a new python object: x = fan_details(name ="Jimmy Flag", previous_address="21, Main Street", age=33) #this line above is really important! Note that now we can initialize an object on one line :-) fans.append(x) print fans[0].previous_addresses print fans[1].previous_addresses |
您的原始类没有使用
下面的代码定义了作为构造函数的
1 2 3 4 5 6 7 | class FanDetails(): def __init__(self, name="", previous_address=None, age=0): self.name = name self.previous_addresses = [] if previous_address: self.previous_addresses.append(previous_address) self.age = age |
准备风扇列表:
1 | fans = [] |
现在的诀窍是:为约翰创建一个FandDetails实例:
1 2 | john = FanDetails("Joe Blow","4, seaview rd", 42) fans.append(john) |
对吉米也一样:
1 2 | jimmy = FanDetails("Jimmy Flag","21, Main Street", 33) fans.append(jimmy) |
与原始代码的关键区别在于,这些john和jimmy实例是独立的,每个实例都具有
最后,检查一下,这两个家伙的分享确实不多,不合理:
1 2 | print fans[0].previous_addresses print fans[1].previous_addresses |
你会看到:
1 2 | ['4, seaview rd'] ['21, Main Street'] |
列表是可变对象,因此它不会分配新内存…复制X…如果正在迭代…如果没有,则使用不同的变量…
建议…请提供完整的代码(与问题相关)
我相信你有三个问题:
我对代码的更改如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class fan_details: name ="" previous_addresses = [] age = 0 fans = [] x = fan_details() x.name ="Joe Blow" x.previous_addresses.append("4, seaview rd") # <--- You had x.previous_address.append("4, seaview rd") x.age = 42; fans.append(x) # x.previous_address.pop(0) x = fan_details() x.name ="Jimmy Flag" x.previous_addresses.append("21, Main Street") # <--- You had x.previous_address.append("21, Main Street") x.age = 33; fans.append(x) print fans[0].previous_addresses # add the 'es' print fans[1].previous_addresses # add the 'es' |
您需要在类定义中使用的变量名和访问时使用的名称中保持一致。