【问题标题】:How to print nested list as new line in CSV?如何在 CSV 中将嵌套列表打印为新行?
【发布时间】:2020-01-02 17:54:51
【问题描述】:

嵌套列表:

AIStable = [['Unknown,Unknown,-,-,9127057/-,-,-,-,0.0°/0.0kn,0.0S/0.0W,-'], ['Tanker,MarshallIslands,USHOU>DOSPM,Jan3,19:00,9683984/538005270,V7CJ5,183/32m,11.4m,112.0°/12.8kn,18.26069N/75.77137W,Jan2,202006:47UTC'], ['Productisnotfound!'], ['Productisnotfound!'], ['Productisnotfound!'], ['Productisnotfound!'], ['Cargoship,Russia,VLADIVOSTOK,RUSSIA,Dec31,00:00,9015785/273213710,UBCT2,119/18m,5.6m,7.9°/0.0kn,43.09932N/131.88229E,Jan1,202009:06UTC'], ['Tanker,Singapore,YEOSU,SK,Jan1,03:00,9370991/566376000,9V3383,100/16m,4.3m,188.0°/0.1kn,34.72847N/127.81362E,Jan2,202007:41UTC'], ['Cargoship,Italy,QINGDAO,Jan1,02:00,9511454/247283400,ICAH,292/45m,18.2m,324.0°/5.4kn,27.80572N/125.07295E,Jan2,202007:20UTC']]

列表中的嵌套列表表示要在 CSV 中添加新行

CSV 文件中所需的输出是:

AIS_Type Flag Destination ETA IMO/MMSI Callsign Length/Beam Current_Draught Course/Speed Coordinates Last_Report
Unknown Unknown - - 9127057/- - - - - 0.0°/0.0kn 0.0S/0.0W - 
Tanker MarshallIslands USHOU>DOSPM Jan3 19:00 9683984/538005270 V7CJ5 183/32m 11.4m 112.0°/12.8kn 18.26069N/75.77137W Jan2 202006:47UTC
Product is not found!

我尝试了以下方法:

AISUpdated = [[''.join(','.join(i).split())] for i in AIStable]
print(AISUpdated)

filename = "vesselsUpdated.csv"
with open(filename, 'w' , newline = '') as f:
    writer = csv.writer(f,delimiter = ",")
    headers = "AIS_Type,Flag,Destination,ETA,IMO/MMSI,Callsign,Length/Beam,Current_Draught,Course/Speed,Coordinates,Last_Report"
    f.write(headers)
    writer.writerows("\n")

    for i in AISUpdated:
        writer.writerows([i])

我获得的输出不反映记录的新列,而它将新列表的所有新记录压缩到 AIS_Type 下的单个列。因此,我希望它以 分隔,并将每个相关数据引用到右列。

【问题讨论】:

  • 为什么不writer.writerows(AISUpdated)
  • 您好 Ron Serruya,我仍然得到相同的结果。结果未与列标题对齐。

标签: python list csv


【解决方案1】:

问题是您的所有列表都只有一个值。
您应该将它们设为实际列表,['Unknown','Unknown','-','-','9127057']

或者这样做:

AISUpdated = [i[0].split(',') for i in AIStable]
with open('file.csv','w') as f:
    writer = csv.writer(f)
    writer.writerow(headers.split(','))
    writer.writerows(AISUpdated)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多