【问题标题】:Append an element from a list to another list将列表中的元素附加到另一个列表
【发布时间】:2017-05-18 17:08:26
【问题描述】:

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

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 函数,然后合并两个列表,但问题是我不知道如何通过使用元素的一部分作为与另一个元素匹配的参考来将一个元素与另一个元素匹配。

【问题讨论】:

  • 您应该阅读如何在 Stack Overflow 上提问的部分
  • 请向我们展示您尝试过的内容,并更具体地说明您遇到的问题。 SO 不是一个让人们为你编写代码的网站。
  • 对不起,我编辑了我的问题..这是我的第一次..

标签: python list coordinates elements


【解决方案1】:
# 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

【讨论】:

  • 哇,它工作得很好。谢谢!我打算将它转换为字典列表,但不幸的是我无法想出一个代码,它会像你所做的那样给出结果。我真的很感激先生。非常感谢。
猜你喜欢
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 2016-02-26
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多