在我们实际业务开发中,肯定会遇到将集合对象的数据遍历完后写入到数据库或者导出为一个csv文件里,如下是一个具体实现的示例demo
代码示例
import pandas as pd
class Test:
calorie = 0
duration = 0
flag = 0
def init_object():
"""
init class atrributes
:return: list
"""
test = Test()
test.calorie = 20
test.duration = 50
test.flag = 1
list = []
# add obj to list
list.append(test.__dict__)
test = Test()
test.calorie = 30
test.duration = 60
test.flag = 0
# add obj to list
list.append(test.__dict__)
print(list)
return list
def obj_csv( obj_list):
"""
:param obj_list:
:return: csv
"""
# convert list to Dataframe
df = pd.DataFrame(obj_list)
print(df)
# take dataframe to csv file
df.to_csv("output.csv", index=None)
obj_list = init_object()
obj_csv(obj_list)