使用Python自动化无聊的东西,第4章练习

时间:2015-05-24 14:01:57

标签: python list

我是新手,现在正在做Al Sweigar的书。在第4章的练习中,他问以下内容,

假设您有一个列表列表,其中内部列表中的每个值都是一个字符的字符串,如下所示:

 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', '.', '.', '.'],
         ['.', '.', '.', '.', '.', '.']] 

您可以将grid [x] [y]视为绘制的“图片”的x坐标和y坐标处的字符      带有文字字符。 (0,0)原点位于左上角      角落,x坐标向右增加,而w      y坐标下降。复制上一个网格值,然后      编写使用它来打印图像的代码。

..OO.OO.. 
.OOOOOOO. 
.OOOOOOO. 
..OOOOO.. 
...OOO... 
....O....

所以我编写了代码并且它完成了他所要求的内容,但我认为它编写得非常糟糕,我想问你如何改进它。我的代码,

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)

节目输出:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

26 个答案:

答案 0 :(得分:17)

我也是一个新手 - 仅使用本书所涵盖的内容,并记住循环提示中的循环,这是我的答案:

for j in range(len(grid[0])):
    for i in range(len(grid)):
        print(grid[i][j],end='')
    print('')

答案 1 :(得分:8)

>>> print('\n'.join(map(''.join, zip(*grid))))
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

zip(*grid)有效地转换矩阵(在主对角线上翻转),然后将每行连接成一个字符串,然后用换行连接行,这样就可以一次打印整个行。

答案 2 :(得分:3)

我有另一个简单的解决方案,非常类似于仅使用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])

打印声明的输出:

  

。 。 O O. O O.

如您所见,它是心脏网格的第一行。我们需要 0 计算到 len(grid [0]) , - 这是指的项目数量第一个列表,你也可以输入6。所以,我需要的是两个互相计数的运算符。空的print语句用于换行符。如果我们不使用它,它会打印出同一行上的所有字符或每行上的每个字符。

解决方案:

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

输出:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

答案 3 :(得分:3)

您可以解决问题的一种方法(给出书中的提示)是定义行和列。给定列表有9行(列表元素)和6列(每个元素的长度)。

显然问题就变成了 -

a)打印第1行的所有列值 b)打印第2行的所有列值 ......等等

一旦我们测量了预先打印的行数和列数,这种方法就可以“标准化”

以下程序说明了这样做的一种方法 -

val dfA = sparkSession.sqlContext.sql("SELECT COLUMN1 FROM MY_VIEW")
val dfB = sparkSession.sqlContext.sql("SELECT COLUMN2 FROM MY_VIEW")     
val mergedDF = dfA.select(dfA.col("COLUMN1").alias("COLUMN3")).union(dfB.select(dfB.col("COLUMN2").alias("COLUMN3")))

val distinctColumnDF = mergedDF.filter(mergedDF.col("COLUMN3").contains("city")).distinct().collect()

logger.debug("No.of Distinct Rows="+distinctColumnDF.count());

答案 4 :(得分:3)

  update Products
  set quantity=0
  where quantity is null

仅使用了我在前几章中学到的信息。我非常感谢通过更先进的技术阅读相同的问题。

答案 5 :(得分:2)

作者说要在循环中使用循环。这是我的答案:

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)

答案 6 :(得分:1)

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 b in range(6):
    for i in range(9):
        print(grid[i][b],end='')
    print('')    

答案 7 :(得分:0)

如果按照本书在练习题提示中所说的去做,我们可以构造一个嵌套的for循环来做到这一点。我们可以使用文字来定义循环的范围(即6和9)。

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 i in range(6):
    for j in range(9):
        print(grid[j][i], end = '')
    print()

结果:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

要使其更通用和更适用,我们可以将其放在函数中。然后使用len()函数概括内部和外部循环参数的范围,并将网格传递给它。

def Rotate(f_grid)
    for i in range(len(f_grid[0]):         # using the len() function lets us pass 
        for j in range(len(f_grid)):       # any rectangular list of list to it
            print(f_grid[j][i], end = '')
        print()
 
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','.','.','.'],
        ['.','.','.','.','.','.']]

Rotate(grid)

结果:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

现在,如果您发现有关使用本书的提示进行操作的某些信息,则位置grid[0][0]保持不变,并且grid[8][0]变为位置grid[0][8]。如果在网格中进行快速替换,则可以在调用该函数时看到它的效果。

grid = [['B','.','.','.','.','D'],
        ['.','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','.','.','.'],
        ['A','.','.','.','.','C']]

Rotate(grid)

结果是旋转的镜像:

B.OO.OO.A
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
D...O...C

如果我们只想要旋转的图像该怎么办?反转内部循环。我们的功能变为:

def Rotate(f_grid)
    for i in range(len(f_grid[0]):  
        for j in range(len(f_grid) - 1, -1, -1): # reverse the inner loop
            print(f_grid[j][i], end = '')
        print()

调用该函数时生成的图像现在为:

A.OO.OO.B
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
C...O...D

它只是旋转了90度,而不是旋转并转置。

现在,我对此进行个人讨论。如何重新排列对象,以便在内存中拥有一个新对象然后进行打印?我知道这个问题只是说打印,但是仅仅知道如何打印它会有多大用处?使用join方法或numpy可能有更好的方法,但是在这本书的这一点上,初学者可能不了解它们,也不可能以这种方式回答问题。这确实需要导入我们在上一章中学到的复制模块(我认为?)

import copy

def Rotate(f_grid)
    # temporary list for a row
    temp_list = []
    # local storage for the new_grid 
    new_grid = []  
    
    # outer loop to iterate over columns
    for i in range(len(f_grid[0]):
        # inner loop to iterate over rows in reverse         
        for j in range(len(f_grid) - 1, -1, -1):
            # add element to the temporary list       
            temp_list.append(f_grid[i][j])

        # add temporary list to new grid as element        
        new_grid.append(copy.copy(temp_list))
        
        #clear the temporary list   
        temp_list.clear()

    return new_grid

# input
old_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','.','.','.'],
            ['.','.','.','.','.','.']]

grid = Rotate(old_grid)

# nested loop to print out each element of the new grid                                                          
for i in range(len(grid)                        
    for j in range(len(grid[0]))
        print(grid[i][j], end = '')
    print()

非转置的90度顺时针旋转结果:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

PS我可能也应该添加一些错误处理。也许以后再说。

答案 8 :(得分:0)

我刚开始读这本书,这是我想出的,看起来很简单。

library(dplyr)

df %>%
  group_by(date, market, gender, age) %>%
  summarise(cust = cust[type=='Active'] - cust[type=='New'], 
            orders = orders[type=='Active'] - orders[type=='New'], 
            type = 'old') %>%
  bind_rows(df)

#  date   market gender age    cust orders type  
#  <fct>  <fct>  <fct>  <fct> <int>  <int> <chr> 
#1 Apr-18 UK     Female U20    2000   5500 old   
#2 Apr-18 UK     Female U20    1000   1500 New   
#3 Apr-18 UK     Female U20    1000   1750 Reac  
#4 Apr-18 UK     Female U20    3000   7000 Active

输出:

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', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]


def final(grid_solve, count):
    empty = ""
    for i in grid_solve:
        empty += i[count]

    return empty


total = 0

while total != len(grid[0]):
    print(final(grid, total))
    total += 1

答案 9 :(得分: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', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

count = 0
while count < len(grid):
    print()
    try:
        for x in range(len(grid)):
            print(grid[x][count], end='')
    except IndexError:
        break

    count += 1

答案 10 :(得分:0)

简单方法:

for i in range(len(grid[1])):
    for row in grid:
        print (row[i], end='')
    print()

答案 11 :(得分:0)

def grid(l):
    for i in range(len(l)):
        print('')

        for j in range(len(l[i])):
            s=l[j][i]
            print(s,end='')

这也照顾了逗号。

答案 12 :(得分: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', '.', '.', '.'],
    ['.', '.', '.', '.', '.', '.']]

def love_grid(name):

    xyz = int(len(list(name)) - 1)

    for a in range(0, len(list(name))):

        print(name[a][0], end="")
        if a == xyz:
            print()
            break

    for a in range(0, len(list(name))):

        print(name[a][1], end="")
        if a == xyz:
           print()
           break

    for a in range(0, len(list(name))):

        print(name[a][2], end="")
        if a == xyz:
            print()
            break

   for a in range(0, len(list(name))):

        print(name[a][3], end="")
        if a == xyz:
            print()
            break

   for a in range(0, len(list(name))):

        print(name[a][4], end="")
        if a == xyz:
           print()
           break

   for a in range(0, len(list(name))):

       print(name[a][5], end="")
        if a == xyz:
           print()
           break



love_grid(grid)

答案 13 :(得分:0)

也是python的新手,我的答案如下,它的确有效。

for i in range(0,6,1):
    for j in range(0,8,1):     
        print(grid[j][i], end='')
    print('')

答案 14 :(得分: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', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

for i in range(len(grid[0])):
    col=[col[i] for col in grid]
    print(*col, sep='')

答案 15 :(得分:0)

我也是新手,我只使用了本书所涵盖的内容。这是我的代码。

for i in range(len(grid[0])):
               for j in range(len(grid)):
                   if j == (len(grid)-1):
                       print(grid[j][i])
                   else:
                       print(grid[j][i], end='')

答案 16 :(得分:0)

for j in range(len(grid[:6])):
  # print(grid[0][j]) 
    for i in range(len(grid)):
        print(grid[i][j], end='')
    print()

注释掉的部分在第一行打印出一个单独的点。 O图本身是正确的,第一列上缺少其他一些点。

答案 17 :(得分:0)

我的尝试,也是通过组合for和while。不像以前的答案那么漂亮,但对我来说仍然足够好。

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', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]
x=0 #counter
y=0 #counter

for y in range(len(grid[x])): #for each y in sublists
    new_str=""                  #create temporary new string to house the sublists
    while x <= len(grid)-1:     #for each x in list
        new_str += grid[x][y]   
        x+=1                    #add every x in a string while keeping y steady
    print(new_str)              #print string of x's while y steady
    x=0                         #set x to 0 in order to start again on next iteration of y

答案 18 :(得分:0)

你甚至可以这样做

for i in range(len(grid[])):
    for j in range(len(grid)):
        print(grid[j][i],end = " ")

    print()

答案 19 :(得分:0)

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()

^没有评论的代码。

想想Al所要求的模式。 [0] [0],[0] [1],[0] [2] ... [8] [0],[8] [1],[8] [2]。因此,您基本上希望第一个用于指示从哪个列表中提取数据,然后在其中用于选择要打印的索引。结束关键字arg也很重要。

答案 20 :(得分:0)

我还从作者那里得到提示,在循环中使用循环。所以我实际上只是使用了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

输出

..00.00..
.0000000.
.0000000.
..00000..
...000...
....0....         

答案 21 :(得分:0)

嘿伙计们我是python的新手,这是我的答案。

for i in range(len(grid[1])):
 print(' ')
 for z in range(len(grid)):
  print(grid[z][i], end='')

答案 22 :(得分:0)

重要的是要记住,练习的想法是用你在本章学到的东西来解决它,所以在循环中使用循环的一种方式:

def grilla(x):
    for y in range(6):
        print()
        for i in range(len(x)):
            print(x[i][y], end='')
grilla(grid)

答案 23 :(得分:0)

很好的解决方案!我使用map()并不是那么舒服。关于练习,我给自己设置了将网格翻转90度的挑战。

首先,它使网格的列表数与原始网格中单个列表的长度相同(以获得x轴)。然后,它将原始网格的每个列表的第一个(或第n个)元素附加到新网格的第一个(或第n个)列表,并打印出新网格的每一行。

可以用更少的代码行完成,但这里是:

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)

编辑:语法。

答案 24 :(得分:-1)

for x in range (0,6):
    for y in range (0,9):
        print (grid[y][x], end='')
    print ('')

答案 25 :(得分:-2)

b=len(grid)  
for y in range(b-3):  
    print('\n')  
    for x in range(b):  
        print(grid[x][y], end=' ')