You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套字符串列表中按指定索引切片字符串

问题解决方案

完整实现代码

list_of_strings = [['01abcdefghijklmnoprs00'], ['02abcdefghijklmnoprs55'], ['03abcdefghijklmnoprs'], ['04abcdefghijklmnoprs11'], ['05abcdefghijklmnoprs22']]
idx_row_list =  [[1, 2], [0, 3], [1, 4]]
idx_col_list = [[10, 12], [8, 12], [8, 12]]
slice_length = 4

Output = []

# 遍历每组行索引与对应列起始索引
for rows, cols in zip(idx_row_list, idx_col_list):
    group_substrings = []
    # 处理当前组内的每个行-列索引对
    for row_idx, col_start in zip(rows, cols):
        # 获取目标字符串(list_of_strings中每个元素为单元素列表,需取[0])
        target_str = list_of_strings[row_idx][0]
        # 按起始索引+切片长度提取子串
        substring = target_str[col_start : col_start + slice_length]
        group_substrings.append(substring)
    Output.append(group_substrings)

print(Output)

执行结果

[['jklm', 'lmno'], ['ghij', 'lmno'], ['ghij', 'lmno']]

逻辑说明

  • 配对索引组:通过zip将idx_row_list和idx_col_list一一对应,保证每组行索引使用对应的列切片规则。
  • 提取目标字符串:list_of_strings的每个元素是单元素列表,因此需要通过[0]取出实际字符串内容。
  • 切片提取子串:以col_start为起始位置,向后截取slice_length个字符,确保每次提取的子串长度固定为4。

内容的提问来源于stack exchange,提问作者mod13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:30:14