python - 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,因此此列表的顺序很重要。对象的第一个值应该是名称属性。
我该如何解决这个问题?
解决方案
您的列表是无序的集合列表,请改用列表或元组
cList.append({c.name, c.address})
应该是(或者)
cList.append((c.name, c.address))
cList.append([c.name, c.address])
推荐阅读
- wpf - 为什么属性窗口中没有出现 Right 和 Bottom 属性?
- php - 从 MySQL 数据库中获取记录的问题
- android - recyclerview的简单项目动画和预测动画有什么区别?
- vb.net - 跟踪 Azure Blob 存储中的上传进度
- node.js - 在模块中定义一个变量并返回它(NodeJs)
- python - 使用 numpy.random.randn() 生成的正态分布的平均值不是“0”
- c++ - Error C2420 : illegal symbol in first operand
- node.js - 在 NODE Sequalize 中批量创建时出错?
- go - Golang中RWMutex的属性
- uwp - 白标 UWP 应用程序