python代码以表格格式写入csv

时间:2017-08-09 10:14:58

标签: python list csv dictionary

[('01', ['name abc', 'age 32', 'address addr123']), ('02', ['name def', 'age 22', 'address addr456'])]

我希望此列表以CSV格式写入以下格式。一些时间表可能包含更多的值。所以没有硬编码。     表格格式的csv中的预期输出

id   name  age   address
01   abc   32    addr123
02   def   22    addr456

3 个答案:

答案 0 :(得分:1)

import csv

data = [('01', ['name abc', 'age 32', 'address addr123']), ('02', ['name def', 'age 22', 'address addr456 789'])]

with open(path_to_csv, 'w') as csv_file:
    writer = csv.DictWriter(csv_file, 'id name age address'.split())
    writer.writeheader()
    for row_id, rest in data:
        row = {'id': row_id}
        for item in rest:
            key, value = item.split(' ', maxsplit=1)
            row[key] = value
        writer.writerow(row)

答案 1 :(得分:0)

或者,您可以使用public static void sort(ArrayList<Number> list) { Number temp = 0; for (int i = 0; i < list.size() - 1; i++) { for (int j = 1; j < list.size(); j++) { if (list.get(j).doubleValue() < list.get(i).doubleValue()) { temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); } } } } ,这绝对可以应对不同的行长,例如:

pandas

编辑:这确实假设你的价值观中没有空格,就像

一样
import pandas as pd

data = [('01', ['name abc', 'age 32', 'address addr123']),
        ('02', ['name def', 'age 22'])] # example of a shorter row



df = pd.DataFrame.from_dict({i:{a.split()[0]:a.split()[1] for a in j} for i,j in data},
            orient='index')

df.to_csv('filename.csv')

但我认为到目前为止所有答案都是正确的。

答案 2 :(得分:0)

让我们假设列名将被排序。例如,名称将始终显示在列中。下面的代码将正常工作。此外,您不需要任何额外的库。

arr = [('01', ['name abc', 'age 32', 'address addr123']), ('02', ['name def', 'age 22', 'address addr456'])]
columnName = ["id"]
output = []
for l in arr:
    ID = l[0]
    val = l[1]
    line = str(ID) + '\t'
    for x in val:
        y = x.split(' ')
        if y[0] not in columnName:
            columnName.append(y[0])
        line += str(y[1]) + '\t'
    line += '\n'
    output.append(line)

colLine = ''
for i in columnName:
    colLine += str(i) + '\t'
colLine += '\n'
output = [colLine] + output
f = open("output.csv", 'w')
for x in output:
    f.write(x)
f.close()