首頁 >後端開發 >Python教學 >python list文法學習

python list文法學習

高洛峰
高洛峰原創
2017-01-13 16:37:541409瀏覽

創建:list = [5,7,9]
取值與改值:list[1] = list[1] * 5
列表尾插入:list.append(4)
去掉第0個值並回傳第0個值的數值:list.pop(0)
去掉第0個值但不回傳數值:del(list[0])
去掉具體某個值:list.remove(35)

函數function:
無參數:def function():
一個參數:def function(x):
2個參數:def function(y):
任意個參數:def add_function(*args):

一個參數:
一個參數:range (n)  從第0位開始數n個位
兩個參數:range(m,n) 從第m位開始到第n-1位,遞增間隔為1
三個參數:range(m,n, i) 從第m位開始到第n-1位,遞增間隔為i
 for item in list:  和for i in range(len(list)): 等價

對list中的元素以separator作為間隔輸出: print separator.join(list)
如: list = ['a','b','c','d']   一般的print list會輸出: ['a','b','c', 'd']。
而print " ".join(list) 會輸出:a b c d(必須是雙的雙引號,單的雙引號不起作用)

接受鍵盤輸入:
guess_row = int(raw_input("Guess Row:"))

下面是一個自己寫的小程式:產生一個方陣和隨機的位置,叫玩家猜這個生成的位置是哪裡

from random import randint
def creat_board(length):
    board = []
    for i in range(length):
        board.append(['O'] * length)
    return board
def print_board(x):
    for row in x:
        print " ".join(row)
def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0,len(board[0]) - 1)

length = int(raw_input("Enter board's length you:"))
board = creat_board(length)
print_board(board)
turns = int(raw_input("Enter turns you want to play:"))
for turn in range(turns):
    ship_row = random_row(board)
    ship_col = random_col(board)
    print "This is " + str(turn + 1) + "th time to guess:"
    guess_row = int(raw_input("Enter the row you guess:"))
    guess_col = int(raw_input("Enter the col you guess:"))

    if guess_row == ship_row and guess_col == ship_col:
        print "You win!"
        break
    else:
        if (guess_row < 0 or guess_row > len(board) - 1) or (guess_col < 0 or guess_col > len(board) - 1):
            print "Incorrect input!"
            if turn == turns - 1:
                print "Turns out!"
        elif board[guess_row][guess_col] == &#39;X&#39;:
            print "You have guessed it already!"
            if turn == turns - 1:
                print "Turns out!"
        else:
            print "You guess wrong!"
            board[guess_row][guess_col] = &#39;X&#39;
            print_board(board)
            if turn == turns - 1:
                print "Turns out!"

曾經犯的錯誤:
1.創建board函數忘記返回一個board,所以它一直為空,導致後面的操作都越界了;
2.生成隨機位置的時候,位置row和col的命名一直是跟生成的函數名一樣(random_row=random_row(board)),導致TypeError: 'int' object is not callable錯誤。

更多python list文法學習相關文章請關注PHP中文網!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn