简体   繁体   中英

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]]

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 ?

For example:

num = 3
print([[*range(1, i + 1)] for i in range(1, num + 1)])

Output:

[[1], [1, 2], [1, 2, 3]]

output will be something like this [[1],[1,2],[1,2,3], … [1,2,3, … ]]

You might combine range with list comprehension to get desired result, for example for 5:

n = 5
sublists = [list(range(1,i+1)) for i in range(1,n+1)]
print(sublists)

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 .

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('')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM