将列表中的元素附加到另一个列表

Append an element from a list to another list

美好的一天。我需要你们的帮助。我有两个列表如下所示。

List_1= [
    'Sta     Pno     Azimuth      Distance     Latitude     Departure ', 
    'T1      X       170.7011111   22.236       21.9438      -3.593    ', 
    'T1      X       170.0        20.0         19.6962      -3.473    ', 
    'T2      X       30.22833333   6.083        -5.2559      -3.0625   ', 
    'T3      X       154.5155556   98.212       88.6562      -42.2573  ', 
    'T4      CHB     351.4977778   93.637       -92.6079     13.844    ', 
    '' ]

List_2= [
    'Sta     Northing     Easting   ', 
    'T1      2000         2000      ',
    'T2      1500         1600      ', 
    'T3      2400         2200      ', 
    'T4      2600         2800      ', 
    '' ]

我想将车站的北向和东向附加到第一个列表中。请帮忙。到目前为止,我尝试使用 zip 函数然后组合两个列表,但问题是我不知道如何通过使用元素的一部分作为匹配另一个元素的参考来将一个元素与另一个元素匹配。

# deal with headings separately from rest of data.
# also split each heading into a list of string rather than single string.
l1_headings, l2_headings = List_1.pop(0).split(), List_2.pop(0).split()
# put each row of List_1 in a list of dictionary using headings as keys
l1_dicts = [{k:v for k, v in zip(l1_headings, row.split())} for row in List_1 if row != '']
# put each row of List_2 in a dictionary of dictionaries indexed by 'Sta'
l2_by_Sta = {}
for row in List_2:
    if row == '': continue
    d = {k:v for k, v in zip(l2_headings, row.split())}
    l2_by_Sta[d['Sta']] = d
# update l1_dicts from data in l2_by_Sta
for d in l1_dicts:
    d.update(l2_by_Sta[d['Sta']])

l1_dicts 现在包含:

[{'Azimuth': '170.7011111',
  'Departure': '-3.593',
  'Distance': '22.236',
  'Easting': '2000',
  'Latitude': '21.9438',
  'Northing': '2000',
  'Pno': 'X',
  'Sta': 'T1'},
 {'Azimuth': '170.0',
  'Departure': '-3.473',
  'Distance': '20.0',
  'Easting': '2000',
  'Latitude': '19.6962',
  'Northing': '2000',
  'Pno': 'X',
  'Sta': 'T1'},
 {'Azimuth': '30.22833333',
  'Departure': '-3.0625',
  'Distance': '6.083',
  'Easting': '1600',
  'Latitude': '-5.2559',
  'Northing': '1500',
  'Pno': 'X',
  'Sta': 'T2'},
 {'Azimuth': '154.5155556',
  'Departure': '-42.2573',
  'Distance': '98.212',
  'Easting': '2200',
  'Latitude': '88.6562',
  'Northing': '2400',
  'Pno': 'X',
  'Sta': 'T3'},
 {'Azimuth': '351.4977778',
  'Departure': '13.844',
  'Distance': '93.637',
  'Easting': '2800',
  'Latitude': '-92.6079',
  'Northing': '2600',
  'Pno': 'CHB',
  'Sta': 'T4'}]

如果您需要将此数据写入文本文件,请使用 csv.DictWriter