Py学习  »  Python

使用python将存储在列表中的DMS值转换为csv文件

CES • 3 年前 • 1513 次点击  

我有一长串DMS值,如下所示。

lst = ['9', '22', '26.9868', 'N',
       '118', '23', '48.876', 'E',
       '9', '22', '18.6132', 'N',
       '118', '23', '5.2188', 'E',
       '9', '19', '41.4804', 'N',
       '118', '19', '23.1852', 'E']

我想以以下格式将此数据写入csv文件:

enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132486
 
1513 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Andrej Kesely
Reply   •   1 楼
Andrej Kesely    3 年前

如果 lst 这是你的问题清单,你可以做:

import csv

with open("data.csv", "w") as f_out:
    csv_writer = csv.writer(f_out)
    i = iter(lst)
    csv_writer.writerow(["deg", "min", "sec", "direction"])
    for t in zip(*[i] * 4):
        csv_writer.writerow(t)

这写着 data.csv :

deg,min,sec,direction
9,22,26.9868,N
118,23,48.876,E
9,22,18.6132,N
118,23,5.2188,E
9,19,41.4804,N
118,19,23.1852,E

LibreOffice截图:

enter image description here

mozway
Reply   •   2 楼
mozway    3 年前

你可以用 numpy pandas :

lst = ['9', '22', '26.9868', 'N',
       '118', '23', '48.876', 'E',
       '9', '22', '18.6132', 'N',
       '118', '23', '5.2188', 'E',
       '9', '19', '41.4804', 'N',
       '118', '19', '23.1852', 'E']

import numpy as np
import pandas as pd
(pd.DataFrame(np.array(lst).reshape(-1,4),
              columns=['deg', 'min', 'sec', 'direction'])
   .to_csv('filename.csv', index=False)
 )

输出文件(作为文本):

deg,min,sec,direction
9,22,26.9868,N
118,23,48.876,E
9,22,18.6132,N
118,23,5.2188,E
9,19,41.4804,N
118,19,23.1852,E