基于Python3 逗號代碼 和 字符圖網(wǎng)格(詳談)
逗號代碼
假定有下面這樣的列表:
spam=['apples','bananas','tofu',' cats']
編寫一個函數(shù),它以一個列表值作為參數(shù),返回一個字符串。該字符串包含所有表項,表項之間以逗號和空格分隔,并在最后一個表項之前插入 and 。例如,將前面的spam列表傳遞給函數(shù),將返回'apples,bananas,tofu,and cats'。但是你的函數(shù)應(yīng)該能夠傳遞給它的任何列表。
代碼如下:
import copy def conFun(nameList): n=len(nameList) newList=copy.copy(nameList) newList.insert(n-1,'and') # print(newList) a=str(newList.pop()) b=str(newList.pop()) c='' c=b+' '+a newOne='' newOne=newList[0] i=1 for j in newList: newOne=newOne+','+newList[i] i=i+1 if i==len(newList): break print(newOne+','+c)
驗證代碼:
================== RESTART: /Users/valen/Documents/test.py ================== >>> spam=['apple','bananas','tofu','cats'] >>> conFun(spam) apple,bananas,tofu,and cats >>>
字符圖網(wǎng)格
假定有一個列表的列表,內(nèi)層列表的每個值都是包含一個字符的字符串,像這樣:
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', '.', '.','.'], ['.', '.', '.', '.', '.','.']]
你可以認(rèn)為grid[x][y]是一幅“圖”在x,y坐標(biāo)處的字符,該圖由文本字符組成。原點(0,0)在左上角,向右x坐標(biāo)增加,向下y坐標(biāo)增加。
復(fù)制前面的網(wǎng)格值,編寫代碼用它打印圖像。
..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O....
提示:你需要使用循環(huán)嵌套循環(huán),打印出grid[0][0],然后grid[1][0],然后grid[2][1],以此類推,知道grid[8][0]。這就完成第一行,所以接下來打印換行。然后程序?qū)⒋蛴〕鰃rid[0][1],然后grid[1][1],然后grid[2][1],以此類推。程序最后將打印出grid[8][5]。
而且,如果你不希望在每次print()調(diào)用后都自動打印換行,記得向print()傳遞end關(guān)鍵字參數(shù)。
import copy 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', '.', '.','.'], ['.', '.', '.', '.', '.','.']] c=[] c=copy.deepcopy(grid) #print(c) gridLen=len(grid) cyctime=len(grid[0]) #print(cyctime) i=0 j=0 for j in range(cyctime): if j < cyctime : for i in range(gridLen): if i < gridLen : print(c[i][j],end=' ') i=i+1 print('\n') j=j+1
輸出如下:
================== RESTART: /Users/valen/Documents/test.py ================== . . 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 . . . . >>>
以上這篇基于Python3 逗號代碼 和 字符圖網(wǎng)格(詳談)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用wxPython獲取系統(tǒng)剪貼板中的數(shù)據(jù)的教程
這篇文章主要介紹了使用wxPython獲取系統(tǒng)剪貼板中的數(shù)據(jù)的教程,wxPython是一個非常受歡迎的Python圖形庫,需要的朋友可以參考下2015-05-05python不相等的兩個字符串的 if 條件判斷為True詳解
這篇文章主要介紹了python不相等的兩個字符串的 if 條件判斷為True詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03