如何使用Python合并列表中相邻的相似字符?
合并列表中相邻的相似字符(Python实现)
嘿,我懂你想要做的事——把分割后列表里相邻的单个#合并成连续的字符串对吧?先看看你现有的代码:
import re test = 'hello###_world###test#test123##' splitter = re.split("(#)", test) splitter = list(filter(None, splitter)) # 输出结果: ['hello', '#', '#', '#', '_world', '#', '#', '#', 'test', '#', 'test123', '#', '#']
下面给你两种实用的解决办法,其中第二种更简洁高效:
方法一:遍历列表手动合并相邻的#
这种方法逻辑直观,适合理解基础的列表遍历和拼接:
result = [] current_hashes = [] for item in splitter: if item == '#': current_hashes.append(item) else: # 如果之前积累了#,先把合并后的#加入结果 if current_hashes: result.append(''.join(current_hashes)) current_hashes = [] result.append(item) # 处理列表末尾可能剩下的# if current_hashes: result.append(''.join(current_hashes)) print(result) # 最终输出: ['hello', '###', '_world', '###', 'test', '#', 'test123', '##']
方法二:优化正则表达式,一步到位得到结果
其实完全可以跳过“分割成单个#再合并”的步骤,直接用正则提取连续的#序列和非#序列,效率更高:
import re test = 'hello###_world###test#test123##' # 正则说明:[^#]+ 匹配一个或多个非#字符;#+ 匹配一个或多个连续的# result = re.findall(r'[^#]+|#+', test) print(result) # 直接得到你想要的结果: ['hello', '###', '_world', '###', 'test', '#', 'test123', '##']
这个正则表达式用|分隔了两种匹配模式,re.findall会把所有符合条件的子串按顺序提取出来,完美符合你的需求,推荐优先使用这种方式。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

