-2

I'm trying to print an list of tuples by comparing the tuple first item to a specified int() but by some mystery reason the tuples with 0 in second term just disappear

The code:

n_vertical = 3
n_horizontal = 3
for x in range(0,n_vertical):
    for y in range(0,n_horizontal):
        area.append((x,y,0))

print(area)
print('''
''')
def representacao_do_mapa(modo):
    if modo == 1:
        n=0
        l_c = []
        for x in area:
            if x[0] == n:
                l_c.append(x)
            else:
                print(l_c)
                l_c = []
                n+=1
representacao_do_mapa(1)

screenshot of output

Textual output:

[(0, 0, 0), (0, 1, 0), (0, 2, 0)]
[(1, 1, 0), (1, 2, 0)]
  • The code does exactly what you said it to do: when it encounters `(n+1,0,0)`, it prints all accumulated elements, increases `n` and goes to the next item. You may be more worried that it doesn't print `(9,*,0)`. –  Jan 19 '19 at 08:30

1 Answers1

3

Problem

You are throwing away the tuple x when you create the new list:

        if x[0] == n:
            l_c.append(x)       # here you append x
        else:
            print(l_c)          # here you print but do nothing with x
            l_c = []            # list empty, x is missing
            n+=1

Solution

def representacao_do_mapa(modo):
    if modo == 1:
        n=0
        l_c = []
        for x in area:
            if x[0] == n:
                l_c.append(x)
            else:
                print(l_c)
                l_c = [x]       # fix here
                n+=1
        print(l_c)              # fix here 

representacao_do_mapa(1)

Beside that - your last list is not going to be printed because the last l_c never get's into the printing part of your code - you have to add that ouside the for-loop over area.

Output (for n_vertical = 3 and n_horizontal = 3:

[(0, 0, 0), (0, 1, 0), (0, 2, 0)]
[(1, 0, 0), (1, 1, 0), (1, 2, 0)]
[(2, 0, 0), (2, 1, 0), (2, 2, 0)]

Optimizations:

You can shorten your code using list comprehensions and list decomposition:

n_vertical = 3
n_horizontal = 3
area = [ (x,y,0) for x in range(n_horizontal) for y in range(n_vertical )]
# create with inner lists
area2 = [ [(x,y,0) for x in range(n_horizontal)] for y in range(n_vertical)]

print(area)

# print each inner list on new line
print(*area2, sep="\n")

Or you can print directly from area:

print(* (area[i*n_horizontal:i*n_horizontal+n_horizontal] 
         for i in range(n_vertical)) , sep="\n")

using a generator expression to slice area into n_horizontal pieces.


More on generator / list expressions: Generator Expressions vs. List Comprehension

More on chunking lists: How do you split a list into evenly sized chunks?

More on list slicing: Understanding slice notation

More on printing: https://docs.python.org/3/library/functions.html#print

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69