[英]List of Sublist in python
I want to write a python code were the output will be something like this [[1],[1,2],[1,2,3], … [1,2,3, … ]] I have this code and has the similar output but the only difference is that it prints all the cases for example if I say that the range is 3 it prints [[1], [1, 2], [1, 3], [1, 2, 3]] and not [[1], [1, 2], [1, 2, 3]]我想写一个 python 代码是 output 将是这样的 [[1],[1,2],[1,2,3], ... [1,2,3, ... ]] 我有这个代码和有类似的 output 但唯一的区别是它打印所有情况,例如如果我说范围是 3 它打印 [[1], [1, 2], [1, 3], [1, 2, 3 ]] 而不是 [[1], [1, 2], [1, 2, 3]]
This is my code这是我的代码
def sub_lists(l):
base = [1]
lists = [base]
for i in range(2, l+1):
orig = lists[:]
new = i
for j in range(len(lists)):
lists[j] = lists[j] + [new]
lists = orig + lists
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
How about using list comprehension
?使用list comprehension
怎么样?
For example:例如:
num = 3
print([[*range(1, i + 1)] for i in range(1, num + 1)])
Output: Output:
[[1], [1, 2], [1, 2, 3]]
output will be something like this [[1],[1,2],[1,2,3], … [1,2,3, … ]] output 将是这样的 [[1],[1,2],[1,2,3], ... [1,2,3, ... ]]
You might combine range
with list
comprehension to get desired result, for example for 5:您可以将range
与list
理解结合起来以获得所需的结果,例如 5:
n = 5
sublists = [list(range(1,i+1)) for i in range(1,n+1)]
print(sublists)
output output
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
Note that range is inclusive-exclusive, thus these +1
.请注意,范围是包含独占的,因此这些+1
。
You should not use a loop inside loops if you intend to add a single number at the end of it only.如果您打算仅在其末尾添加一个数字,则不应在循环内使用循环。
def copyBase(lst):
return lst[:]
def sub_lists(l):
base = [1]
lists = []
for i in range(1, l+1):
lists += [copyBase(base),]
base += [i+1]
return lists
num=int(input("Please give me a number: "));
print(sub_lists(num))
Try this尝试这个
def sub_lists(l):
lists = []
for i in range(l):
sublist = [1]
for i2 in range(i):
sublist.append(i2+2)
lists.append(sublist)
return lists
Implementation With User Input使用用户输入实现
def sub_lists(l):
lists = []
for i in range(l):
sublist = [1]
for i2 in range(i):
sublist.append(i2+2)
lists.append(sublist)
return lists
input_num = int(input('Please Enter a Number: '))
results = sub_lists(input_num)
for i in results:
for i2 in i:
print(str(i2)+' ',end='')
print('')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.