【Python-2.7】list類型

list是Python中的一種數據類型,也就是"列表"。在Python中咱們能夠對list類型進行插入,刪除,修改等操做。app

##新建list類型
>>> ball = ['volleyball','basketball','football','baseball']

##能夠直接打印出list內容
>>> ball
['volleyball', 'basketball', 'football', 'baseball']

##也可使用下標列出,注意下標是從0開始的,負數表示從後往前數
>>> ball[0]
'volleyball'
>>> ball[1]
'basketball'
>>> ball[2]
'football'

##使用append函數,在list最後追加內容
>>> ball.append('ping-pong')
>>> ball
['volleyball', 'basketball', 'football', 'baseball', 'ping-pong']

##選擇位置插入,好比在'volleyball'後面插入'badminton'
>>> ball.insert(1,'badminton')
>>> ball
['volleyball', 'badminton', 'basketball', 'football', 'baseball', 'ping-pong']

##替換list中的某一個元素,好比把'badminton'替換成'bowling'
>>> ball[1]='bowling'
>>> ball
['volleyball', 'bowling', 'basketball', 'football', 'baseball', 'ping-pong']

##使用pop()刪除元素,好比刪除最後的'ping-pong',刪除'bowling'
>>> ball.pop()
'ping-pong'
>>> ball
['volleyball', 'bowling', 'basketball', 'football', 'baseball']
>>> ball.pop(1)
'bowling'
>>> ball
['volleyball', 'basketball', 'football', 'baseball']

##使用len()查詢list中元素個數
>>> ball
['volleyball', 'basketball', 'football', 'baseball']
>>> len(ball)
4
相關文章
相關標籤/搜索