【发布时间】:2018-11-22 10:38:16
【问题描述】:
我在列表中有列名,我想将值 1 分配给这些列名,并将值 0 分配给其余列。 例如。
perms_name = ['name','place','thing']
最初的 CSV 看起来像:
name,age,place,thing,phone_no
我想让 csv 看起来像:
name,age,place,thing,phone_no
1,0,1,1,0
我可以通过这个简单地做到这一点
with open('eggs.csv','a') as csvfile:
fieldname = ["name","age","place","thing","phone_no"]
writer = csv.DictWriter(csvfile,fieldnames=fieldname)
writer.writeheader()
writer.writerow(
{'name': 1,'age':0,'place':1,'thing':1,'phone_no':0}
)
但是他们有更快的方法吗,在这种情况下,它们只有 5 列,如果它们是 100 列,我只想将 1 分配给列表中提到的列。
【问题讨论】:
标签: python python-3.x python-2.7 csv dictionary