如何在Python中创建一个子列表?

问题描述 投票:-3回答:1

我想实现这样的事情。

length_of_list = 3
length_of_sublists = 5

...

output = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

我试了很多次,但我就是不明白怎么做。

谢谢大家的帮助

编辑:我按照要求附上了我的代码! 很明显,它不工作,因为输出的是嵌套列表。如果我违反了一些规则,我很抱歉,我是新来的 :)

length_of_list = 3
length_of_sublist = 5

for i in range(length_of_list):
    list = []
    for j in range(1, length_of_sublist+1):
        list.append(j)
    list.append(list)

print(list)


[1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [1, 2, 3, 4, 5]]]
python list for-loop
1个回答
0
投票

如果你想创建一个嵌套列表,可以考虑使用嵌套列表理解。

>>> length_of_list = 3
>>> length_of_sublists = 5
>>> [[i for i in range(1, length_of_sublists + 1)] for j in range(length_of_list)]
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

0
投票

我不知道你需要这个干什么,但这是你的解决方案

lenght_of_list = 3
length_of_sublists = 5

output = []
for i in range(length_of_list):
    sub_list = []
    for j in range(length_of_sublists):
        sub_list.append(j+1)
    output.append(sub_list)

0
投票

你应该自己试试。如果你尝试了许多可能的方法,这将肯定会对你有所帮助.你不需要一个循环来解决这个问题。只要把这一个循环分解开来。你会明白这个道理。

>>> [list(range(1, length_of_sublists+1))] * length_of_list 
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

当被重复的项目是一个列表时,要小心。列表将不会被克隆:所有的元素都将引用同一个列表!

>>> output[0][0] = 9
>>> output
[[9, 2, 3, 4, 5], [9, 2, 3, 4, 5], [9, 2, 3, 4, 5]]
© www.soinside.com 2019 - 2024. All rights reserved.