首页 > 解决方案 > Python对象列表追加问题

问题描述

我尝试将对象附加到列表然后打印它。

客户.py

class Customer:
def __init__(self,id,name,address,active,created):
    self.id=id
    self.name=name
    self.address=address
    self.active=active
    self.created=created

主文件

import customer
cList=list()

for x in range(5,10):
    c=customer.Customer("","c"+str(x)+" name","c"+str(x)+" adress","","")
    cList.append({c.name, c.address})

for a in cList:
    print(a) 

预期产出

{'c5 名称', 'c5 地址'}
{'c6 名称', 'c6 地址'}
{'c7 名称', 'c7 地址'}
{'c8 名称', 'c8 地址'}
{'c9 名称', 'c9 地址'}

实际输出

{'c5 名称', 'c5 地址'}
{'c6 地址', 'c6 名称'}
{'c7 地址', 'c7 名称'}
{'c8 地址', 'c8 名称'}
{'c9 名称', 'c9 地址'}

当我每次运行代码时,它都会给我不同的结果。我将使用此列表将数据插入 MySQL,因此此列表的顺序很重要。对象的第一个值应该是名称属性。

我该如何解决这个问题?

标签: pythonlist

解决方案


您的列表是无序的集合列表,请改用列表或元组

cList.append({c.name, c.address})

应该是(或者)

cList.append((c.name, c.address))
cList.append([c.name, c.address])

推荐阅读