这是我的清单,
['Query Date :September 07, 2017',
'Address :Aguila arizona',
'Latitude :33.9428069', 'Longitude :-113.1740805',
'Elevation :2170.4 Feet',
'Elevation Limitation: ASCE 7* Ground Snow **LoadElevation** 3,000 feet: Ground Snow Load is0 ',
'Elevation > 3,000 and 4,500 feet: Ground Snow Load is5 ',
'Elevation > 4,500 and 5,400 feet: Ground Snow Load is10 ',
'']
我想拆分列表中第5个元素的特定单词(即LoadElevation)。因此在加载后它应该被拆分。
输出应该像
['Query Date :September 07, 2017',
'Address :Aguila arizona', 'Latitude :33.9428069',
'Longitude :-113.1740805', 'Elevation :2170.4 Feet',
'Elevation Limitation: ASCE 7* Ground Snow **Load',
'Elevation** 3,000 feet: Ground Snow Load is0 ',
'Elevation > 3,000 and 4,500 feet: Ground Snow Load is5 ',
'Elevation > 4,500 and 5,400 feet: Ground Snow Load is10 ',
'']
伙计们帮助我。提前谢谢。
答案 0 :(得分:1)
使用re.findall()
函数的简短解决方案:
import re
l = ['Query Date :September 07, 2017', 'Address :Aguila arizona', 'Latitude :33.9428069', 'Longitude :-113.1740805', 'Elevation :2170.4 Feet', 'Elevation Limitation: ASCE 7* Ground Snow LoadElevation 3,000 feet: Ground Snow Load is0 ', 'Elevation > 3,000 and 4,500 feet: Ground Snow Load is5 ', 'Elevation > 4,500 and 5,400 feet: Ground Snow Load is10 ', '']
l[5:6] = re.findall(r'.*\Load|Elevation.*', l[5])
print(l)
输出:
['Query Date :September 07, 2017', 'Address :Aguila arizona', 'Latitude :33.9428069', 'Longitude :-113.1740805', 'Elevation :2170.4 Feet', 'Elevation Limitation: ASCE 7* Ground Snow Load', 'Elevation 3,000 feet: Ground Snow Load is0 ', 'Elevation > 3,000 and 4,500 feet: Ground Snow Load is5 ', 'Elevation > 4,500 and 5,400 feet: Ground Snow Load is10 ', '']
答案 1 :(得分:0)
Asumming你的“分裂元素”只出现一次,得到它的索引,切片到那个索引,插入你想要的任何东西,然后添加列表的其余部分。
>>> a = [1, 2, 'SplitHere', 3, 4]
>>> idx = a.index('SplitHere')
>>> a[:idx] + ['Split', 'Here'] + a[idx+1:]
[1, 2, 'Split', 'Here', 3, 4]
我对分割进行了硬编码,因为你没有给出任何分割目标词的规则或标准。
答案 2 :(得分:0)
对于通用,您可以尝试以下代码:
import re
for index,line in enumerate(list1):
if("LoadElevation" in line):
newList = re.split("LoadElevation",line)
new_index = index
list1 = list1[:index]+ [ele + "Load" if index1%2==0 else "Elevation"+ele for index1,ele in enumerate(newList)] + list1[index+1:]
print list1 #['Query Date :September 07, 2017', 'Address :Aguila arizona', 'Latitude :33.9428069', 'Longitude :-113.1740805', 'Elevation :2170.4 Feet', 'Elevation Limitation: ASCE 7* Ground Snow **Load', 'Elevation** 3,000 feet: Ground Snow Load is0 ', 'Elevation > 3,000 and 4,500 feet: Ground Snow Load is5 ', 'Elevation > 4,500 and 5,400 feet: Ground Snow Load is10 ', '']