基于字符串中的整数拆分列表为子列表的更优Python实现方案
嗨,这个需求其实有非常Pythonic的实现方式,不用手动遍历索引那么繁琐!我给你推荐两种常用的简洁方法,都是利用Python内置工具来搞定:
方法一:用
itertools.groupby分组 itertools.groupby是Python专门用来分组的工具,搭配列表推导式可以快速实现分组逻辑。需要注意的是,groupby只会对连续的相同键分组,所以我们需要先把原列表按数字键排序:
from itertools import groupby file_list = ['text_1.jpg', 'othertext_1.jpg', 'text_2.jpg', 'othertext_2.jpg', 'text_3.jpg', 'anothertext_3.jpg'] # 定义提取分组键的函数:获取文件名末尾的数字 def get_group_key(filename): # 拆分文件名,提取下划线后的数字部分并转成整数 return int(filename.split('_')[-1].replace('.jpg', '')) # 先按数字键排序,确保同数字的文件连续 sorted_files = sorted(file_list, key=get_group_key) # 分组并转成嵌套列表 grouped_list = [list(group) for _, group in groupby(sorted_files, key=get_group_key)] print(grouped_list) # 输出:[['text_1.jpg', 'othertext_1.jpg'], ['text_2.jpg', 'othertext_2.jpg'], ['text_3.jpg', 'anothertext_3.jpg']]
如果你的文件名格式更复杂(比如包含多个下划线,像text_abc_1.jpg),可以用正则表达式更健壮地提取数字:
import re def get_group_key(filename): # 匹配末尾的 _数字.jpg 格式 match = re.search(r'_(\d+)\.jpg$', filename) return int(match.group(1)) if match else -1
方法二:用字典收集分组(适合乱序列表)
如果你的原列表是乱序的,不想先整体排序,可以用字典来按数字键收集文件,最后再按数字顺序输出分组:
from collections import defaultdict file_list = ['text_2.jpg', 'othertext_1.jpg', 'text_1.jpg', 'othertext_2.jpg', 'anothertext_3.jpg', 'text_3.jpg'] # 用defaultdict自动创建空列表作为值 group_dict = defaultdict(list) for filename in file_list: # 同样提取数字键 key = int(filename.split('_')[-1].replace('.jpg', '')) group_dict[key].append(filename) # 按数字键的顺序排序,得到嵌套列表 grouped_list = [group_dict[key] for key in sorted(group_dict.keys())] print(grouped_list) # 输出:[['othertext_1.jpg', 'text_1.jpg'], ['text_2.jpg', 'othertext_2.jpg'], ['anothertext_3.jpg', 'text_3.jpg']]
这两种方法都比手动遍历索引更简洁、可读性更高,完全符合Python的"优雅"风格——尽量利用内置工具,避免重复造轮子。
内容的提问来源于stack exchange,提问作者mkohler
相关产品推荐
相关产品推荐

