我有一个如下所示的元组列表
[("color", "blue"), ("size","50"), ("length","60"),("color", "red"), ("size","40")]
我想要一个像这样的 csv
文件(当然没有 Header
,values
)
标题
1. 颜色 |尺寸|长度
值
2. 蓝色 | 50 | 50 60
值
3. 红色 | 40|无
我尝试过这个,但效果不太好
with open('file.csv','w') as out:
for title in final: # list name
titles.append(title[0])
csv_out=csv.writer(out)
csv_out.writerow(titles)
for row in final:
csv_out.writerows(row[1])
最佳答案
尝试这种方法
import pandas as pd
import numpy as np
from collections import defaultdict
t = [("color", "blue"), ("size","50"), ("length","60"),("color", "red"), ("size","40")]
d = dict((y, x) for x, y in t)
res = defaultdict(list)
for key, val in sorted(d.items()):
res[val].append(key)
df = pd.DataFrame.from_dict(res, orient='index').fillna(np.nan).T
df.to_csv("file.csv")
关于python - 元组列表转为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58928731/