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

Python嵌套列表元素分配求助:将6个元素按规则分配至子列表

解决方案

这里给你几种简单易懂的实现方式,都是适合Python新手的写法:

方法一:索引取余循环(最直观)

用元素的索引对3取余,循环对应到3个子列表的位置:

# 示例元素列表和初始嵌套列表
elements = [1, 2, 3, 4, 5, 6]
nested_list = [[], [], []]

# 遍历每个元素,带上索引
for idx, item in enumerate(elements):
    # 索引对3取余,得到0/1/2循环,对应三个子列表
    nested_list[idx % 3].append(item)

print(nested_list)  # 输出: [[1, 4], [2, 5], [3, 6]]

方法二:用itertools.cycle循环子列表

借助itertools.cycle工具重复迭代子列表,写法更简洁:

from itertools import cycle

elements = [1, 2, 3, 4, 5, 6]
nested_list = [[], [], []]

# 把元素和循环的子列表配对,逐个添加
for item, sublist in zip(elements, cycle(nested_list)):
    sublist.append(item)

print(nested_list)

方法三:切片直接生成(一行搞定)

如果不需要在已有嵌套列表上修改,直接用切片语法生成目标嵌套列表:

elements = [1, 2, 3, 4, 5, 6]
nested_list = [elements[i::3] for i in range(3)]

print(nested_list)  # 输出: [[1, 4], [2, 5], [3, 6]]

原理是elements[i::3]表示从索引i开始,每隔3个元素取一个,正好按你的规则分组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:45:50