Domanda

I want to make a table of alternating 1's and 0's using for statements and lists for a given number of rows and columns (similar to the code below). Any ideas as to how I would do this?

#fill elements in left and right columns with ones

ROWS = m
COLUMNS = n
table = []

for i in range(COLUMNS):
    if i ==0 or i == (COLUMNS-1):
        column = [1] * ROWS
    else:
        column = [0] * ROWS
    table.append(column)

for i in range(ROWS):
    for j in range(COLUMNS):
        print(table[j][i], end=" ")
    print()
È stato utile?

Soluzione

Maybe you want something like this:

ROWS = 5
COLUMNS = 5
table = [[1 if i%2==0 else 0 for i in range(COLUMNS)] for j in range(ROWS)]

for row in table:
for cell in row:
    print (cell, end=' ')
print()
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1

OR maybe:

table = [[(i+j)%2 for i in range(COLUMNS)] for j in range(ROWS)]
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0

Altri suggerimenti

You can create the first and the second rows separately and return the copies of them alternatively, like this

def get_table(rows, cols):
    row2,row1 = [i%2 for i in xrange(cols)],[i%2 for i in xrange(1,cols+1)]
    return [row1[:] if i % 2 else row2[:] for i in xrange(rows)]

print get_table(5, 6)

Output

[[0, 1, 0, 1, 0, 1],
 [1, 0, 1, 0, 1, 0],
 [0, 1, 0, 1, 0, 1],
 [1, 0, 1, 0, 1, 0],
 [0, 1, 0, 1, 0, 1]]

I'd go for:

from itertools import cycle, islice

COLUMNS = 5; ROWS = 4
values = cycle([0, 1])
table = [list(islice(values, COLUMNS)) for _ in xrange(ROWS)]
# [[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1]]

This automatically cycles the values and avoiding making copies of existing lists.

Working with even length columns:

COLUMNS = 4; ROWS = 4
values = [cycle([0, 1])]
if COLUMNS % 2 == 0:
    values.append(cycle([1, 0]))
values = cycle(values)

table = [list(islice(next(values), COLUMNS)) for _ in xrange(ROWS)]

I would use itertools.cycle for more readable (faster?) code:

import itertools

rows = cols = 4
even_gen = itertools.cycle((0, 1))
odd_gen = itertools.cycle((1, 0))

even = [next(even_gen) for _ in xrange(cols)]
odd = [next(odd_gen) for _ in xrange(cols)]
both = itertools.cycle((even, odd))
result = [next(both)[:] for _ in xrange(rows)]

EDIT added next(both)[:] to actually return copy of row

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top