user12882840
user12882840

Reputation:

List of list with conditionals

I'm trying to create a list of lists returning specific numbers.

def game(height):
    lstoflst = []
    sublist = []
    for row in range(height):
        sublist.append(row)
        if len(sublist)>2:
            sublist.remove(sublist[0])
            lstoflst.append(list(sublist))
    return lstoflst

Output: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

Desired Output: [[0,0],[0,1],[1,1],[0,2],[1,2],[2,2],[0,3],[1,3],[2,3],[3,3]]

I'm confused if I need to add conditionals to make this work and if so, how would I implement it into my code.

Upvotes: 1

Views: 56

Answers (2)

Kenan
Kenan

Reputation: 14094

As stated by @jez

n = 4
[[x, xmax] for xmax in range(n) for x in range(xmax+1)]

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

Without a list comprehension, you can print along the way

lst = []
for xmax in range(n):
    #print(lst)
    for x in range(xmax+1):
        #print(lst)
        lst.append([x, xmax])

Upvotes: 1

You probably need to perform an inner loop:

def game(height):
    lstoflst = []
    sublist = []
    for row in range(height):
        for second_row in range(height):
          
            insert_into_sublist(row)
            insert_into_sublist(second_row)

    return lstoflst.sort()

def insert_into_sublist(element_to_insert, sublist, lstoflst):

    sublist.append(element_to_insert)

    if len(sublist) == 2:
        lstoflst.append(list(sublist))
        sublist.clear()
        sublist.append(second_row)

Upvotes: 0

Related Questions