如何在Python中以特定的方式重新组织列表

2024-09-27 07:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我想做的是,如果你有以下清单:

example_list=['This', 'is', 'QQQQQ', 'an', 'QQQQQ', 'example', 'list', 'QQQQQ', '.']

我希望它重组如下:

example_list=['This is', 'an', 'example list', '.']

注意qq是如何被用作占位符的。所以,基本上我希望qqs之间的所有东西都是一个列表元素。我该怎么做?你知道吗

我也看过其他关于join()函数的文章,但我遇到的问题是,如果有多个单词,就在它们之间加一个空格。你知道吗


Tags: 函数an元素列表isexample文章this
3条回答

尝试joinstrip()一起去除空白

answer = [s.strip() for s in ' '.join(map(str, example_list)).split('QQQQQ')]
print (answer)

输出

['This is', 'an', 'example list', '.']

您可以使用^{}

>>> from itertools import groupby
>>> example_list=['This', 'is', 'QQQQQ', 'an', 'QQQQQ', 'example', 'list', 'QQQQQ', '.']
>>> [' '.join(g) for k, g in groupby(example_list, lambda x: x == 'QQQQQ') if not k]
['This is', 'an', 'example list', '.']

或者甚至用^{}比较,正如@tobias_k在评论中所建议的:

>>> [' '.join(g) for k, g in groupby(example_list, key='QQQQQ'.__eq__) if not k]
['This is', 'an', 'example list', '.']

使用简单的迭代。你知道吗

例如:

example_list=['This', 'is', 'QQQQQ', 'an', 'QQQQQ', 'example', 'list', 'QQQQQ', '.']

res = [[]]
for i in example_list:
    if i == "QQQQQ":
        res.append([])
    else:
        res[-1].append(i)
print([" ".join(i) for i in res])

输出:

['This is', 'an', 'example list', '.']

相关问题 更多 >

    热门问题