列表和你可以用它們做的事情。包括索引,切片和變異!
1.列表
Python 中的 List 表示有序的值序列:
In [1]:
primes = [2, 3, 5, 7]
我們可以把其他類型的事情列入清單:
In [2]:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
我們甚至可以列一個清單:
In [3]:
hands = [
['J', 'Q', 'K'],
['2', '2', '2'],
['6', 'A', 'K'], # (Comma after the last element is optional)
]
# (I could also have written this on one line, but it can get hard to read)
hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]
列表可以包含不同類型的變量:
In [4]:
my_favourite_things = [32, 'raindrops on roses', help]
# (Yes, Python's help function is *definitely* one of my favourite things)
1.1索引
可以使用方括號訪問單個列表元素。
哪個行星離太陽最近? Python 使用從零開始的索引,因此第一個元素的索引為0。
In [5]:
planets[0]
Out[5]:
'Mercury'
下一個最近的星球是什么?
In [6]:
planets[1]
Out[6]:
'Venus'
哪個行星離太陽最遠?
列表末尾的元素可以用負數(shù)訪問,從 -1開始:
In [7]:
planets[-1]
Out[7]:
'Neptune'
In [8]:
planets[-2]
Out[8]:
'Uranus'
1.2切片
前三顆行星是什么? 我們可以通過切片來回答這個問題:
In [9]:
planets[0:3]
Out[9]:
['Mercury', 'Venus', 'Earth']
planets[0:3]
是我們詢問從索引 0 開始并一直到 但不包括 索引 3 的方式。
起始和結(jié)束索引都是可選的。如果省略起始索引,則假定為 0。因此,我可以將上面的表達式重寫為:
In [10]:
planets[:3]
Out[10]:
['Mercury', 'Venus', 'Earth']
如果我省略了結(jié)束索引,它被假定為列表的長度。
In [11]:
planets[3:]
Out[11]:
['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
也就是說,上面的表達意思是“給我從索引3開始的所有行星”。
我們還可以在切片時使用負指數(shù):
In [12]:
# All the planets except the first and last
planets[1:-1]
Out[12]:
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']
In [13]:
# The last 3 planets
planets[-3:]
Out[13]:
['Saturn', 'Uranus', 'Neptune']
1.3列表修改
列表是“可變的”,這意味著它們可以“就地”修改。
修改列表的一種方法是為索引或片表達式賦值。
例如,假設(shè)我們想重命名火星:
In [14]:
planets[3] = 'Malacandra'
planets
Out[14]:
['Mercury',
'Venus',
'Earth',
'Malacandra',
'Jupiter',
'Saturn',
'Uranus',
'Neptune']
嗯,這是相當(dāng)拗口。讓我們通過縮短前三個行星的名稱來補償。文章來源:http://www.zghlxwxcb.cn/news/detail-797778.html
In [15]:文章來源地址http://www.zghlxwxcb.cn/news/detail-797778.html
planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets
到了這里,關(guān)于4、python列表Lists的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!