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

Convert DMS values stored in a list to csv file using python

我有一长串 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 文件:

您可以使用 numpypandas:

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

如果 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 的屏幕截图: