我是python的新手。我在使用python从列表创建csv文件时遇到问题。我有一个这样的清单:
mylist = ['Steve, Male, 28 years, 170 cm, 60 kg',
'Anna, Female, 26 years, 163 cm, 55 kg',
'Joe, Male, 27 years, 174 cm, 63 kg']
我想通过在数字数据值中添加标题和删除单位,从上面的列表中创建一个csv文件。我想要的是这样的:
+-----------+--------+-----+------+------+
| name | sex | age |height|weight|
+-----------+--------+-----+------+------+
| Steve | Male | 28 | 170 | 60 |
+-----------+--------+-----+------+------+
| Anna | Female | 26 | 163 | 55 |
+-----------+--------+-----+------+------+
| Joe | Male | 27 | 174 | 63 |
+-----------+--------+-----+------+------+
到目前为止,这是我的代码:
with open('data.csv', 'w', newline='') as csvfile:
header = ['name', 'sex', 'age', 'height', 'weight']
writers = csv.writer(csvfile, delimiter=',')
writers.writerow(header)
for row in mylist:
writers.writerow([row])
我遇到了代码。
答案 0 :(得分:1)
完整的解决方案是:
with open('data.csv', 'w', newline='') as csvfile:
header = ['name', 'sex', 'age', 'height', 'weight']
writers = csv.writer(csvfile, delimiter=',')
writers.writerow(header)
for row in mylist:
writers.writerow([x.split()[0] for x in row.split(', ')])
BTW我认为不需要newline=''
以下是最后一行代码中发生的魔术的解释:
我们用包含逗号和空格的分隔符拆分行。然后我们将获取每个项目的第一个单词(即.split()[0]
部分)。
答案 1 :(得分:0)
您的myList是单个列表。要么将它列为列表,mylist中的每个条目都是这一行的每一行,然后使用你的代码:
mylist = [['Steve, Male, 28 years, 170 cm, 60 kg'],
['Anna, Female, 26 years, 163 cm, 55 kg'],
['Joe, Male, 27 years, 174 cm, 63 kg']]
答案 2 :(得分:0)
numpy用于以下代码
import numpy as np
mylist = ['Steve, Male, 28 years, 170 cm, 60 kg',
'Anna, Female, 26 years, 163 cm, 55 kg',
'Joe, Male, 27 years, 174 cm, 63 kg']
table = np.array(["name", "sex", "age" , "height", "weight"])
for i in range(len(mylist)):
row = np.array(mylist[i].split(","))
table = np.vstack((table, row.reshape((1, row.shape[0]))))
np.savetxt("result.csv", table, fmt='%s', delimiter=",")
答案 3 :(得分:0)
使用 pandas (今天的表的首选库):
import pandas as pd
header = ['name', 'sex', 'age', 'height', 'weight']
mylist = ['Steve, Male, 28 years, 170 cm, 60 kg',
'Anna, Female, 26 years, 163 cm, 55 kg',
'Joe, Male, 27 years, 174 cm, 63 kg']
df = pd.DataFrame((i.split(', ') for i in mylist), columns=header)
df.to_csv('data.csv',index=False)
创建:
name,sex,age,height,weight
Steve,Male,28 years,170 cm,60 kg
Anna,Female,26 years,163 cm,55 kg
Joe,Male,27 years,174 cm,63 kg