重新加入列表中的特定分割字符串PYTHON

时间:2018-10-19 21:03:24

标签: python split

我有一个清单,其中包含带有测量单位的值,我想删除它们,原始清单如下:

['Dawn:', 'Sunrise:', 'Moonrise:', 'Dusk:', 'Sunset:\xa0', 'Moonset:', 'Daylight:', 'Length:', 'Phase:', 'Temperature', 'Dew\xa0Point ', 'Windchill', 'Humidity', 'Heat Index', 'Apparent Temperature', 'Solar Radiation', 'Evapotranspiration Today', 'Rainfall\xa0Today', 'Rainfall\xa0Rate', 'Rainfall\xa0This\xa0Month', 'Rainfall\xa0This\xa0Year', 'Rainfall\xa0Last Hour', 'Last rainfall', 'Wind\xa0Speed\xa0(gust)', 'Wind\xa0Speed\xa0(avg)', 'Wind Bearing', 'Beaufort\xa0F1', 'Barometer\xa0', 'Rising slowly']
['07:30', '08:04', '17:03', '19:05', '18:31', '01:45', '11:35', '10:27', 'Waxing Gibbous', '13.7\xa0°C', '11.4\xa0°C', '13.7\xa0°C', '86%', '13.7\xa0°C', '13.0\xa0°C', '0\xa0W/m²', '0.15\xa0mm', '0.0\xa0mm', '0.0\xa0mm/hr', '36.4\xa0mm', '36.4\xa0mm', '0.0\xa0mm', '2018-10-14 08:52', '6.1\xa0kts', '2.6\xa0kts', '229° SW', 'Light air', '1026.89\xa0mb', '0.27\xa0mb/hr']

要删除度,kts,mb等度量单位,请遵循以下方法:

    newlist = [word for line in test for word in line.split()]
    #print(newlist)
    testlist = ['°C', 'W/m²', 'mm','mm/hr', 'mb','kts', 'mb/hr', '%']
    t = [x for x in newlist for d in testlist if d in x]

    s = [r for r in newlist if r not in testlist]

在此代码之后,我能够删除所有单位,但是然后,以字符串分隔并且由诸如 Waxing Gibbous 之类的空格分隔的值将以逗号分隔。我有可能用空格重新加入他们吗?

代码结果:

['Dawn:', 'Sunrise:', 'Moonrise:', 'Dusk:', 'Sunset:\xa0', 'Moonset:', 'Daylight:', 'Length:', 'Phase:', 'Temperature', 'Dew\xa0Point ', 'Windchill', 'Humidity', 'Heat Index', 'Apparent Temperature', 'Solar Radiation', 'Evapotranspiration Today', 'Rainfall\xa0Today', 'Rainfall\xa0Rate', 'Rainfall\xa0This\xa0Month', 'Rainfall\xa0This\xa0Year', 'Rainfall\xa0Last Hour', 'Last rainfall', 'Wind\xa0Speed\xa0(gust)', 'Wind\xa0Speed\xa0(avg)', 'Wind Bearing', 'Beaufort\xa0F1', 'Barometer\xa0', 'Rising slowly']
['07:30', '08:04', '17:03', '19:05', '18:31', '01:45', '11:35', '10:27', 'Waxing', 'Gibbous', '13.7', '11.4', '13.7', '86%', '13.7', '13.0', '0', '0.15', '0.0', '0.0', '36.4', '36.4', '0.0', '2018-10-14', '08:52', '5.2', '2.4', '188°', 'S', 'Light', 'air', '1026.21', '0.23']

从中获取数据的主要源代码:

Data origin source code

任何帮助将不胜感激,谢谢

1 个答案:

答案 0 :(得分:1)

因此,您之前确定的源数据来自一个称为分组的字典(请考虑是否可以放回去并显示一个很棒的示例)

您希望从组中将所有键作为标题,并将值作为值,但替换所有不需要的符号。

下面的代码从分组的dict开始为您执行此操作,并将标头和值存储在2个单独的列表中:

headers = []
values = []
testlist = ['°C', 'W/m²', 'mm','mm/hr', 'mb','kts', 'mb/hr']

for i in a[0]:
    for k,v in i.items():
        headers.append(k)
        values.append(v)

for idx,v in enumerate(values):
    for t in testlist:
        values[idx] = values[idx].replace(t,'')

for h,v in zip(headers,values):
    print('Header: {} , Value : {}'.format(h,v))

如果概述源数据的起始位置,然后概述预期的输出,这绝对对将来有所帮助。