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

标签 python python-2.7 python-3.x

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

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)

关于python - 根据重复的单词拆分现有列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705259/

相关文章:

javascript - Python爬虫使用Selenium和PhantomJS获取DOM信息

Python装饰器: TypeError: function takes 1 positional argument but 2 were given

python-3.x - 如何在 PyCharm 中调试 Python 包

python - 赋值错误之前引用的局部变量 python 3

python - 将 Celery Chunks 与对象或整数序列一起使用

python - 在 PyQt 中的菜单栏下方显示图像

python - 我想检查输入是否是 python 代码

python - 在 PyQt 中将变量从一个类传递到另一个类

python - 如何在 tkinter Entry 小部件中插入临时文本?

python - geopy 类型错误 : geocode() missing 1 required positional argument: 'query'