我想创建一个交替1和0的表,使用for语句和列表给定数量的行和列(类似于下面的代码)。有关如何做到这一点的任何想法?
#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()
答案 0 :(得分:2)
也许你想要这样的东西:
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
或者也许:
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
答案 1 :(得分:1)
您可以分别创建第一行和第二行,并交替返回它们的副本,如下所示
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)
<强>输出强>
[[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]]
答案 2 :(得分:1)
我去找:
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]]
这会自动循环值并避免复制现有列表。
使用偶数长度列:
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)]
答案 3 :(得分:0)
我会使用itertools.cycle
来获得更易读(更快?)的代码:
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)]
编辑添加next(both)[:]
实际返回行