您的位置:首页 > 编程语言 > Python开发

Python学习笔记 - list和tuple

2015-06-28 17:30 676 查看
demo 1

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

>>> classmates = ['Michael', 'Bob', 'Tracy'] #
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> len(classmates)
3
>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'
>>> classmates[2]
'Tracy'
>>> classmates[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> classmates[-1] #直接获取最后一个位置的元素
'Tracy'

>>> classmates[-1]
'Tracy'
>>> classmates[-2]
'Bob'
>>> classmates[-3]
'Michael'
>>> classmates[-4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

>>> classmates.append('Adam') # 插入到尾部
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']
>>> classmates.insert(1, 'Jack') # 插入到指定位置,1
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

>>> classmates.pop() # 删除list末尾的元素
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']
>>> classmates.pop(1) # 删除指定位置的元素
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']
>>> classmates[1] = 'Sarach' # 替换
>>> classmates
['Michael', 'Sarach', 'Tracy']

>>> L = ['Apple', 123, True] # list元素的数据类型可以不同
>>> L
['Apple', 123, True]
>>> s = ['python', 'java', ['asp', 'php'], 'scheme'] # list可以包含list
>>> s
['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s) # 可以将s看成二维数组
4
>>> L = [] #空list
>>> len(L)
0


tuple不可变

>>> classmates = ('Michael', 'Bob', 'Tracy')
>>> classmates
('Michael', 'Bob', 'Tracy')
>>> classmates[0]  = 'Se'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。

tuple的陷阱:当定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来,eg

>>> t = (1, 2)
>>> t
(1, 2)
>>> t = ()
>>> t
()
注意定义一个只有1元素的tuple,如果如下定义:

>>> t = (1)
>>> t
1
定义的不是tuple,是1这个数,因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,按小括号进行计算,计算结果是1。

那么定义只有1元素的tuple时,必须加一个逗号,来消除歧义

>>> t = (1,)
>>> t
(1,)
>>>
Python在显示只有1个元素的tuple时,也会加一个逗号,以免误解成数学计算以上的括号。

如果tuple包含了list,其中的list内容是可变的,tuple没变是因为它指向的还是同样的list的地址,只是list中的内容变了,所以tuple还是没变。

>>> t = ('a', 'b', ['A', 'B'])
>>> t
('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])


练习:

>>> L = [
... ['Apple', 'Google', 'Microsoft'],
... ['Java', 'Python', 'Ruby', 'Php'],
... ['Adam', 'Bart', 'Lisa']
... ]
>>> L
[['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'Php'], ['Adam', 'Bart', 'Lisa']]
>>> print(L[0][0])
Apple
>>> print(L[1][1])
Python
>>> print(L[2][2])
Lisa
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: