Edm*_*mon 23 python csv tuples
我有一个按值排序的元组列表.它们的形式(name,count)
是count是每个唯一名称的出现次数.
我想取这个列表并将其转换为CSV,其中每个名称都是列标题,每个值都是单行的列值.
有什么建议怎么办?谢谢.
daw*_*awg 54
你可以这样做:
import csv
data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]
with open('ur file.csv','wb') as out:
csv_out=csv.writer(out)
csv_out.writerow(['name','num'])
for row in data:
csv_out.writerow(row)
# You can also do csv_out.writerows(data) instead of the for loop
Run Code Online (Sandbox Code Playgroud)
输出文件将具有:
name,num
"smith, bob",2
carol,3
ted,4
alice,5
Run Code Online (Sandbox Code Playgroud)
import csv
lol = [(1,2,3),(4,5,6),(7,8,9)]
item_length = len(lol[0])
with open('test.csv', 'wb') as test_file:
file_writer = csv.writer(test_file)
for i in range(item_length):
file_writer.writerow([x[i] for x in lol])
Run Code Online (Sandbox Code Playgroud)
输出
1,4,7
2,5,8
3,6,9
Run Code Online (Sandbox Code Playgroud)
请注意,在 python 3 中尝试可能会出现TypeError: a bytes-like object is required, not 'str' in python and CSV 中提到的错误。
考虑用于with open('ur file.csv','w') as out:
python 3。