简体   繁体   English

如何添加/附加到python对象?

[英]How to add/append to python object?

I have a python object that was created and defined by swagger editor. 我有一个由swagger编辑器创建和定义的python对象。 I have written a program to populate it. 我已经编写了一个程序来填充它。 However, instead of appending it, it keeps replacing previous entries. 但是,它没有替换它,而是继续替换以前的条目。 Below is my code; 下面是我的代码;

from xlrd import open_workbook
from abc_model import BES as bes
for sheet in wb.sheet():
    if sheet.name == "ABC"
    number_columns = sheet.ncols
    for i in range(2,number_of_columns):
        xyz = bes(name = sheet.cell(19,i).value))
        model.abc_model = xyz
print(model)

This only prints and asssign the content of column 4 (assuming there are total 4 columns). 这仅打印和分配第4列的内容(假设总共有4列)。 However, it should have contents of columns 3 and 4. Any idea what I am doing wrong? 但是,它应该具有第3列和第4列的内容。您知道我在做什么错吗?

Instead of model.abc_model = xyz try model.abc_model += xyz 代替model.abc_model = xyz尝试model.abc_model += xyz

You're setting your column to the last value obtained, rather than adding them together with your iteration. 您将列设置为获得的最后一个值,而不是将它们与迭代一起添加。 This is why you're only getting the second value, and not the first or both. 这就是为什么您只获得第二个值,而不是第一个或两个都得到的原因。

As @Dylan Smite mentioned, use model.abc_model += xyz . 如@Dylan Smite所述,使用model.abc_model += xyz This line of code basically mean that model.abc_model = model.abc_model + xyz . 这行代码基本上意味着model.abc_model = model.abc_model + xyz It means you add xyz to model.abc_model and then assign it back to model.abc_model 这意味着您将xyz添加到model.abc_model ,然后将其分配回model.abc_model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM