python - 如何创建嵌套列表并在每个嵌套中放置特定数量的元素?列表和它的嵌套元素总是不一样的

标签 python python-3.x list nested-lists

这就是我正在做的,

    amount = [2, 2, 3]
my_list = ['name_zero', 'name_one', 'score_three', 'score_nine', 'age_zero', 'age_ten', 'age_six']
output = []

for i in amount:
    output.append(my_list[:i])

print(output)
  • 我得到了什么:

    [['name_zero', 'name_one'], ['name_zero', 'name_one'], ['name_zero', 'name_one', 'score_three']]

我的代码的问题是,它附加了相同的元素,接收这样的输出的正确方法应该是什么?

# [['name_zero', 'name_one'], ['score_three', 'score_nine'], ['age_zero', 'age_ten', 'age_six']]

最佳答案

尝试:

amount = [2, 2, 3]
my_list = [
    "name_zero",
    "name_one",
    "score_three",
    "score_nine",
    "age_zero",
    "age_ten",
    "age_six",
]
output = []

i = iter(my_list)
for v in amount:
    output.append([next(i) for _ in range(v)])

print(output)

打印:

[
    ["name_zero", "name_one"],
    ["score_three", "score_nine"],
    ["age_zero", "age_ten", "age_six"],
]

关于python - 如何创建嵌套列表并在每个嵌套中放置特定数量的元素?列表和它的嵌套元素总是不一样的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68658145/

相关文章:

python - 如何使用 PyCurl 设置 GET 参数?

Python - 从循环构建字符串

c++ - 使用循环在链表的前面插入一个节点

python - 如何将嵌套字典转换为列表字符串

python - 如何在 Python 中对列表使用 sum() 函数?

python - 在类中实例化线程

python - Python for 循环实际上是如何工作的?

python - 如何处理没有结尾斜杠的空 HTML 元素?

python-3.x - 在 fastai 库中使用 download_data() 和 untar_data()

python - 如何搜索字符串、提取其中的一部分并将其用作变量