使用 Python 自动化无聊的事情,第 4 章练习
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30424355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automate the Boring Stuff With Python, Chapter 4 Exercise
提问by Donj10
I'm newbie and doing Al Sweigar's book at the moment. In chapter 4's exercise, he asks the following,
我是新手,目前正在写 Al Sweigar 的书。在第 4 章的练习中,他提出以下问题:
Say you have a list of lists where each value in the inner lists is a one-character string, like this:
假设您有一个列表列表,其中内部列表中的每个值都是一个单字符字符串,如下所示:
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', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The (0, 0) origin will be in the upper-left corner, the x-coordinates increase going right, and w the y-coordinates increase going down. Copy the previous grid value, and write code that uses it to print the image.
您可以将 grid[x][y] 视为使用文本字符绘制的“图片”的 x 和 y 坐标处的字符。(0, 0) 原点将在左上角,x 坐标向右增加,w y 坐标向下增加。复制先前的网格值,并编写使用它打印图像的代码。
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
So I have written the code and it does what he asks for but I think its very poorly written and I wanted to ask you how can I improve it. My code,
所以我已经编写了代码并且它满足了他的要求,但我认为它写得非常糟糕,我想问你我该如何改进它。我的代码,
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', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
newString = ''
for i in range(len(grid)):
newString += str(grid[i][0])
newString1 = '\n'
for i in range(len(grid)):
newString1 += str(grid[i][1])
newString2 = '\n'
for i in range(len(grid)):
newString2 += str(grid[i][2])
newString3 = '\n'
for i in range(len(grid)):
newString3 += str(grid[i][3])
newString4 = '\n'
for i in range(len(grid)):
newString4 += str(grid[i][4])
newString5 = '\n'
for i in range(len(grid)):
newString5 += str(grid[i][5])
print(newString+newString1+newString2+newString3+newString4+newString5)
Output of program:
程序输出:
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
采纳答案by Stefan Pochmann
>>> print('\n'.join(map(''.join, zip(*grid))))
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
The zip(*grid)
effectively transposes the matrix (flip it on the main diagonal), then each row is joined into one string, then the rows are joined with newlines so the whole thing can be printed at once.
的zip(*grid)
有效转置矩阵(翻转它的主对角线),则每一行被接合到一个字符串,则该行被用换行接合,从而整个事情可以一次打印。
回答by Matt Larsh
The author says to use a loop in a loop. Here is my answer:
作者说在循环中使用循环。这是我的回答:
def reformat(myList):
for i in range(0,len(myList[0])):
myStr = ''
for j in range(0,(len(myList))):
myStr += myList[j][i]
print(myStr)
回答by kilocatt
I'm a newbie too - Using only what the book had covered, and keeping in mind the loop within a loop hint, this is my answer:
我也是新手 - 仅使用本书涵盖的内容,并记住循环提示中的循环,这是我的答案:
for j in range(len(grid[0])):
for i in range(len(grid)):
print(grid[i][j],end='')
print('')
回答by dasdachs
Nice solutions! I'm not nearly that comfortable using map(). Regarding the exercise I set myself a challenge to flip the grid 90-degrees.
不错的解决方案!我不太习惯使用 map()。关于练习,我给自己设定了一个挑战,将网格翻转 90 度。
First it makes a grid that has the same number of lists as the length of single list in the original grid (to get the x-axis). Then it appends the first (or n-th) elements of each list of the original grid to the first (or n-th) list of the new grid and prints out each line of the new grid.
首先,它创建一个网格,该网格的列表数量与原始网格中单个列表的长度相同(以获取 x 轴)。然后它将原始网格的每个列表的第一个(或第 n 个)元素附加到新网格的第一个(或第 n 个)列表中,并打印出新网格的每一行。
It could be done in fewer lines of code, but here it is:
它可以用更少的代码行完成,但这里是:
def character_picture_grid(x):
"""The character_picture _grid print a grid list
with list(9 x 6) and rotates it 90-degrees."""
# Flip the grid.
newGrid = [[] for i in range(len(x[0]))]
for i in range(len(newGrid)):
for a in range(len(x)):
newGrid[i].append(x[a][i])
# Print the grid
for i in newGrid:
print(i)
EDIT: Grammar.
编辑:语法。
回答by dasdachs
Its important to keep in mind that the idea of the exercise is to resolve it with what you′ve learn till this chapter, so one way using loop in a loop:
重要的是要记住,练习的想法是用你在本章之前学到的知识来解决它,所以在循环中使用循环的一种方法:
def grilla(x):
for y in range(6):
print()
for i in range(len(x)):
print(x[i][y], end='')
grilla(grid)
回答by easymanatee
Hey guys im am new to python, here is my answer.
嘿伙计们,我是 Python 的新手,这是我的答案。
for i in range(len(grid[1])):
print(' ')
for z in range(len(grid)):
print(grid[z][i], end='')
回答by Stanley Wilkins
I have another simple solution, very similar to other solutions using only for loops. But one thing I seem to did different is that I used two augmented operators, one inside the inside-loop, one outside of it. I thought it would be useful after figuring out what we are asked for.
我有另一个简单的解决方案,与仅使用 for 循环的其他解决方案非常相似。但我似乎做了不同的一件事是我使用了两个增强运算符,一个在内部循环内,一个在循环外部。我认为在弄清楚我们的要求后它会很有用。
print(grid[0][0],
grid[1][0],
grid[2][0],
grid[3][0],
grid[4][0],
grid[5][0],
grid[6][0],
grid[7][0],
grid[8][0])
Output of Print Statement:
打印语句的输出:
. . O O . O O . .
. . 哦。哦。.
As you can see, it's the first line of the heart grid. We need to count from 0to len(grid[0]), -that's the number of items in the first list, you can just type 6 as well.So, all I needed is two operators counting inside each other. The empty print statement is for line-breaks. If we don't use it, it prints out either all characters on the same line, or each character on each line.
如您所见,它是心形网格的第一行。我们需要从0 数到len(grid[0]),-这是第一个列表中的项目数,您也可以只输入 6。所以,我所需要的只是两个相互计数的运算符。空的打印语句用于换行。如果我们不使用它,它要么打印出同一行上的所有字符,要么打印出每行上的每个字符。
Solution:
解决方案:
def printer(grid):
for m in range(len(grid[0])):
print()
for n in range(len(grid)):
print (grid[n][m],end="")
n+=1
m+=1
Output:
输出:
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
回答by ET1919
I also took the hint from the author to use the loop within a loop. So I actually just used a combination of a while and for loop. Here is my code:
我还从作者那里得到了在循环中使用循环的提示。所以我实际上只是使用了 while 和 for 循环的组合。这是我的代码:
#First I copied the grid as the author instructs
grid = [['.','.','.','.','.','.'],
['.','0','0','.','.','.'],
['0','0','0','0','.','.'],
['0','0','0','0','0','.'],
['.','0','0','0','0','0'],
['0','0','0','0','0','.'],
['0','0','0','0','.','.'],
['.','0','0','.','.','.'],
['.','.','.','.','.','.']]
# I set two global variables x and y. I will use x to iterate through
# the while loop and y to increment the index in the inner list
x = 0
y = 0
# set the condition for the while loop to limit it to the length of the list
# and also to limit it to the length of the inner list which doesn't exceed index 5
while x < len(grid) and y <= 5:
for item in range(len(grid)):
print(grid[item][y], end='')
y += 1 # increment y after iteration of a for loop
print('') # print blank line
x += 1 # increment x after iteration of for loop go through for loop again
Output
输出
..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....
回答by matt
for x in range (0,6):
for y in range (0,9):
print (grid[y][x], end='')
print ('')
回答by Adam Bruneau
def heart():
#Set your range to the length of the first list in grid.
for y in range(len(grid[0])):
#This print('') will break every printed line once the second for loop completes below.
print('')
#Set your second for loop to the length of the number of lists within grid.
for x in range(len(grid)):
#Add an end keyword arg to allow for consecutive str prints without new lines.
print(grid[x][y],end='')
heart()
def heart():
for y in range(len(grid[0])):
print('')
for x in range(len(grid)):
print(grid[x][y],end='')
heart()
^ code without the comments.
^ 没有注释的代码。
Think of the pattern Al is asking for. [0][0],[0][1],[0][2]...[8][0],[8][1],[8][2]. So you basically want the first for to indicate which list to pull data from and then a for within that to choose the index to print. The end keyword arg is crucial as well.
想想 Al 要求的模式。[0][0],[0][1],[0][2]...[8][0],[8][1],[8][2]。因此,您基本上希望第一个 for 指示从哪个列表中提取数据,然后在其中选择一个 for 来选择要打印的索引。end 关键字 arg 也很重要。