如何将字符串拆分重组为含2个单词的子字符串?
从单词列表重组为双词组字符串
方法一:循环切片拼接
这是最直观的实现方式,通过步长为2的循环遍历单词列表,每次取相邻两个单词用空格拼接:
words = ['john', 'had', 'a', 'little', 'blue', 'car'] result = [] # 从索引0开始,每次跳2个位置 for i in range(0, len(words), 2): # 拼接当前索引和下一个索引的单词 result.append(f"{words[i]} {words[i+1]}") # 输出目标格式的结果 for item in result: print(repr(item))
运行后输出:
'john had' 'a little' 'blue car'
方法二:切片+zip配对拼接
利用列表切片分离出奇数位和偶数位的单词,再通过zip配对后拼接,代码更简洁:
words = ['john', 'had', 'a', 'little', 'blue', 'car'] # words[::2]取索引0、2、4的单词,words[1::2]取索引1、3、5的单词 result = [f"{first} {second}" for first, second in zip(words[::2], words[1::2])] # 输出结果 for item in result: print(repr(item))
方法三:通用分组工具(itertools)
如果需要处理更通用的分组需求(比如每组单词数不是2),可以用itertools的分组工具:
from itertools import zip_longest def grouper(iterable, group_size, fillvalue=None): args = [iter(iterable)] * group_size return zip_longest(*args, fillvalue=fillvalue) words = ['john', 'had', 'a', 'little', 'blue', 'car'] # 按每组2个单词分组,再拼接成字符串 result = [' '.join(group) for group in grouper(words, 2)] for item in result: print(repr(item))
内容的提问来源于stack exchange,提问作者keeran_q789
相关产品推荐
相关产品推荐

