如何从嵌套字符串列表中按指定索引切片字符串
问题解决方案
完整实现代码
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
相关产品推荐
相关产品推荐

