我试图将列表拆分为新列表。这是最初的清单:
initList =['PTE123', '', 'I', 'am', 'programmer', 'PTE345', 'based', 'word',
'title', 'PTE427', 'how', 'are', 'you']
如果我想将基于PTExyz的列表拆分为新列表:
newList = ['PTE123 I am programmer', 'PTE345 based word title', 'PTE427 how are you']
如何使用重复项PTExyz为一般情况开发合适的算法?
谢谢!
答案 0 :(得分:3)
算法将是这样的。
迭代列表。找到以s
开头的字符串PTE
。将其分配给temp
字符串,该字符串初始化为空字符串。使用s
添加每个下一个字符串temp
,除非该字符串以PTE
开头。在这种情况下,如果temp
字符串不为空,则将其附加到您的result
列表中,否则添加带有temp
的字符串。
ls = ['PTE123', '', 'I', 'am', 'programmer', 'PTE345', 'based', 'word', 'title', 'PTE427', 'how', 'are', 'you']
result = []
temp = ''
for s in ls:
if s.startswith('PTE'):
if temp != '':
result.append(temp)
temp = s
else:
if temp == '':
continue
temp += ' ' + s
result.append(temp)
print(result)
修改强>
为了处理模式PTExyz
,您可以使用正则表达式。在这种情况下,代码将是这样的,其中行是s.startswith('PTE')
:
re.match(r'PTE\w{3}$', s)
答案 1 :(得分:1)
我认为它会起作用
l =['PTE123', '', 'I', 'am', 'programmer', 'PTE345', 'based', 'word','title', 'PTE427', 'how', 'are', 'you']
resultlist = []
s = ' '.join(l)
str = s.split('PTE')
for i in str:
resultlist.append('PTE'+i)
resultlist.remove('PTE')
print resultlist
答案 2 :(得分:1)
它适用于正则表达式PTExyz
import re
l =['PTE123', '', 'I', 'am', 'programmer', 'PTE345', 'based', 'word',
'title', 'PTE427', 'how', 'are', 'you']
pattern = re.compile(r'[P][T][E]\d\d\d')
k = []
for i in l:
if pattern.match(i) is not None:
k.append(i)
s = ' '.join(l)
str = re.split(pattern, s)
str.remove('')
for i in range(len(k)):
str[i] = k[i] + str[i]
print str
答案 3 :(得分:0)
>>> list =['PTE123', '', 'I', 'am', 'programmer', 'PTE345', 'based', 'word','title', 'PTE427', 'how', 'are', 'you']
>>> index_list =[ list.index(item) for item in list if "PTE" in item]
>>> index_list.append(len(list))
>>> index_list
[0, 5, 9, 13]
>>> [' '.join(list[index_list[i-1]:index_list[i]]) for i,item in enumerate(index_list) if item > 0 ]
<强>输出强>
['PTE123 I am programmer', 'PTE345 based word title', 'PTE427 how are you']