2016-03-29 74 views
0

我目前正在学习Python 3,计划将它用于物理和作为爱好。我正在使用使用Python自动化无聊的东西:Al Sweigart的初学者实用编程列表和打印模式

我目前被困在练习题之一。

Screenshot of Problem

这是我迄今所做的。

grid = [['.', '.', '.', '.', '.', '.'], 
    ['.', 'O', 'O', '.', '.', '.'], 
    ['O', 'O', 'O', 'O', '.', '.'], 
    ['O', 'O', 'O', 'O', 'O', '.'], 
    ['.', 'O', 'O', 'O', 'O', 'O'], 
    ['O', 'O', 'O', 'O', 'O', '.'], 
    ['O', 'O', 'O', 'O', '.', '.'], 
    ['.', 'O', 'O', '.', '.', '.'], 
    ['.', '.', '.', '.', '.', '.']] 

for x in grid : # x is a list value 
    for y in x : #y is a string - a character in x 
     if x.index(y) < len(x) - 1 : 
      print(grid[grid.index(x)][x.index(y)], end = "") 
     else : 
      print(grid[grid.index(x)][x.index(y)]) 

但是,结果是这样的。

.......OO...OOOO..OOOOO. 
.OOOOOOOOOO. 
OOOO...OO......... 

请指导我一个正确的解决方案。我在查看问题时遇到了一些麻烦。谢谢:)

回答

0
grid = [['.', '.', '.', '.', '.', '.'], 
     ['.', 'O', 'O', '.', '.', '.'], 
     ['O', 'O', 'O', 'O', '.', '.'], 
     ['O', 'O', 'O', 'O', 'O', '.'], 
     ['.', 'O', 'O', 'O', 'O', 'O'], 
     ['O', 'O', 'O', 'O', 'O', '.'], 
     ['O', 'O', 'O', 'O', '.', '.'], 
     ['.', 'O', 'O', '.', '.', '.'], 
     ['.', '.', '.', '.', '.', '.']] 

rot2 = zip(*grid[::-1]) 

for i in rot2: print i 

# ('.', '.', 'O', 'O', '.', 'O', 'O', '.', '.') 
# ('.', 'O', 'O', 'O', 'O', 'O', 'O', 'O', '.') 
# ('.', 'O', 'O', 'O', 'O', 'O', 'O', 'O', '.') 
# ('.', '.', 'O', 'O', 'O', 'O', 'O', '.', '.') 
# ('.', '.', '.', 'O', 'O', 'O', '.', '.', '.') 
# ('.', '.', '.', '.', 'O', '.', '.', '.', '.') 
0

看一看代码:

#!python3 

grid = [ 
    ['.', '.', '.', '.', '.', '.'], 
    ['.', 'O', 'O', '.', '.', '.'], 
    ['O', 'O', 'O', 'O', '.', '.'], 
    ['O', 'O', 'O', 'O', 'O', '.'], 
    ['.', 'O', 'O', 'O', 'O', 'O'], 
    ['O', 'O', 'O', 'O', 'O', '.'], 
    ['O', 'O', 'O', 'O', '.', '.'], 
    ['.', 'O', 'O', '.', '.', '.'], 
    ['.', '.', '.', '.', '.', '.']] 

# The original. The empty-string separator 
# is used to join the characters. 
for row in grid: 
    print(''.join(row)) 

print('------------------------------------') 

# Using the zip() function to get the columns. 
# The star in front of the grid expands the 
# outer list -- as if you passed the inner 
# lists as the separate arguments of the zip() 
for column in zip(*grid): 
    print(''.join(column)) 

print('------------------------------------') 

# If you want to use indexing, then you need 
# to get the dimensions first. 
leny = len(grid) # the number of rows 
lenx = len(grid[0]) # the number of elements in the first rows 

for x in range(lenx): 
    for y in range(leny): 
     print(grid[y][x], end='') 
    print() 

结果...

...... 
.OO... 
OOOO.. 
OOOOO. 
.OOOOO 
OOOOO. 
OOOO.. 
.OO... 
...... 
------------------------------------ 
..OO.OO.. 
.OOOOOOO. 
.OOOOOOO. 
..OOOOO.. 
...OOO... 
....O.... 
------------------------------------ 
..OO.OO.. 
.OOOOOOO. 
.OOOOOOO. 
..OOOOO.. 
...OOO... 
....O....