Skip to main content
 首页 » 编程设计

python之根据重复的单词拆分现有列表

2025年05月04日24开发

我试图将一个列表拆分为新列表。这是初始列表:

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 的一般情况开发适当的算法?

谢谢!

请您参考如下方法:

算法将是这样的。

遍历列表。查找以PTE 开头的字符串s。将其分配给初始化为空字符串的 temp 字符串。添加每个带有 temp 的下一个字符串 s 除非该字符串以 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)