根据字符串中的整数将列表拆分为子列表

2024-10-05 14:21:39 发布

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

我有一个字符串列表,如下所示:

['text_1.jpg', 'othertext_1.jpg', 'text_2.jpg', 'othertext_2.jpg', ...]

实际上,每个数字有多于2个条目,但这是通用格式。我想将此列表拆分为以下列表:

[['text_1.jpg', 'othertext_1.jpg'], ['text_2.jpg', 'othertext_2.jpg'], ...]

这些子列表基于下划线后的整数。我目前的方法是首先根据上面第一个列表示例中显示的数字对列表进行排序,然后遍历每个索引,如果值与前一个整数的值匹配,则将值复制到新列表中

我想知道是否有一种更简单、更通灵的方式来完成这项任务


Tags: 方法字符串text示例列表排序格式方式
2条回答

尝试:

import re

lst = ["text_1.jpg", "othertext_1.jpg", "text_2.jpg", "othertext_2.jpg"]

r = re.compile(r"_(\d+)\.jpg")
out = {}
for val in lst:
    num = r.search(val).group(1)
    out.setdefault(num, []).append(val)

print(list(out.values()))

印刷品:

[['text_1.jpg', 'othertext_1.jpg'], ['text_2.jpg', 'othertext_2.jpg']]

与@Andrej类似的解决方案:

import itertools
import re


def find_number(s):
    # it is said that python will compile regex automatically
    # feel free to compile first
    return re.search(r'_(\d+)\.jpg', s).group(1)


l = ['text_1.jpg', 'othertext_1.jpg', 'text_2.jpg', 'othertext_2.jpg']
res = [list(v) for k, v in itertools.groupby(l, find_number)]
print(res)
#[['text_1.jpg', 'othertext_1.jpg'], ['text_2.jpg', 'othertext_2.jpg']]

相关问题 更多 >