Python 3.5 |拆分列表并转换为csv

时间:2022-12-10 18:22:22

I have two lists saved in two values. Those look like:

我有两个保存在两个值中的列表。那些看起来像:

project_titles = ['T1', 'T2', 'T3']
project_loc = ['L1', 'L2', 'L3']

Actual I write the values with this Code into a csv:

实际我将此代码的值写入csv:

with open('data.csv', 'w') as f:
    csv.writer(f).writerow(project_titles)

When I turn the csv to an excel I get:

当我将csv转为excel时,我得到:

  • Cell A1 = T1
  • 单元格A1 = T1

  • Cell B1 = T2
  • 单元格B1 = T2

  • Cell C1 = T3
  • 单元C1 = T3

Thats fine, but I need the following result after the csv export:

多数民众赞成,但在csv导出后我需要以下结果:

  • Cell A1 = T1; Cell B1 = L1
  • 单元格A1 = T1;单元格B1 = L1

  • Cell A2 = T2; Cell B2 = L2
  • 单元格A2 = T2;单元格B2 = L2

  • Cell A3 = T3; Cell B3 = L3
  • 细胞A3 = T3;单元格B3 = L3

Do you have an idea?

你有好主意吗?

1 个解决方案

#1


3  

You could use zip() to aggregate elements from two or more lists, then write the resulting rows to the file with csvwriter.writerows():

您可以使用zip()聚合来自两个或多个列表的元素,然后使用csvwriter.writerows()将结果行写入文件:

with open('data.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(project_titles, project_loc))

#1


3  

You could use zip() to aggregate elements from two or more lists, then write the resulting rows to the file with csvwriter.writerows():

您可以使用zip()聚合来自两个或多个列表的元素,然后使用csvwriter.writerows()将结果行写入文件:

with open('data.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(project_titles, project_loc))