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

对整数列表执行批量减1操作并生成嵌套结果列表的需求

解决方案:生成依次对列表元素减1的嵌套列表

嘿,我明白你要做的事了!简单来说就是要对原列表里的每个元素(除了0,从你的示例来看)依次执行减1操作,每次操作后生成一个新列表,最后把所有这些新列表打包成一个嵌套列表对吧?

核心思路

我们需要遍历原列表的每一个元素:

  • 遇到非0元素时,复制原列表(绝对不能直接修改原列表,不然会影响后续操作),然后把当前位置的元素减1
  • 把每次生成的新列表收集起来,最后返回这个收集好的嵌套列表

Python代码实现(匹配你的示例逻辑)

def create_nested_modified_lists(input_list):
    nested_result = []
    # 遍历列表,同时获取索引和元素值
    for index, number in enumerate(input_list):
        # 跳过0元素,不执行减1操作(和示例逻辑一致)
        if number != 0:
            # 复制原列表,避免修改原数据
            modified_list = input_list.copy()
            modified_list[index] -= 1
            nested_result.append(modified_list)
    return nested_result

# 测试你的示例输入
input_example = [1, 2, 3, 0, 4]
output_example = create_nested_modified_lists(input_example)
print(output_example)
# 输出结果和你给的完全一致:[[0, 2, 3, 0, 4], [1, 1, 3, 0, 4], [1, 2, 2, 0, 4], [1, 2, 3, 0, 3]]

如果需要处理所有元素(包括0)

要是你之后想连0元素也一起减1(哪怕变成负数),只需要去掉判断条件就行:

def create_nested_modified_lists_all(input_list):
    nested_result = []
    for index, number in enumerate(input_list):
        modified_list = input_list.copy()
        modified_list[index] -= 1
        nested_result.append(modified_list)
    return nested_result

# 测试
test_input = [1, 0, 2]
print(create_nested_modified_lists_all(test_input))
# 输出: [[0, 0, 2], [1, -1, 2], [1, 0, 1]]

小提示

  • 这里用copy()做浅拷贝就足够了,因为你的列表里都是整数(不可变类型);如果列表里有嵌套结构,记得用copy.deepcopy()来避免意外修改原数据哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:36:54