Python基础三

使用list与tuple

list

talking is cheap, show me the code


>>> classmate=['Michael','Wh0am1','Linux']
>>> len(classmate)   
3
>>> classmate[-1]
'Linux'
>>> classmate[-2]
'Wh0am1'
>>> classmate[-3]
'Michael'
>>> classmate[1]
'Wh0am1'
>>> classmate.append('Windows')  #向classmate这个list末尾追加元素
>>> classmate
['Michael', 'Wh0am1', 'Linux', 'Windows']
>>> calssmate.pop()   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'calssmate' is not defined
>>> classmate.pop()             #删除list末尾元素
'Windows'
>>> classmate
['Michael', 'Wh0am1', 'Linux']
>>> classmate.insert('Windows')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)
>>> classmate.append('Windows')            #向list末尾追加元素
>>> classmate
['Michael', 'Wh0am1', 'Linux', 'Windows']
>>> classmate.insert(1, 'Computer')        #向list1号位插入元素
>>> classmate
['Michael', 'Computer', 'Wh0am1', 'Linux', 'Windows']
>>> classmate.pop(0)                       #删除0号位元素
'Michael'
>>> classmate
['Computer', 'Wh0am1', 'Linux', 'Windows']
>>> a= ['Hacker']                      
>>> classmate.append(a)                    #list元素也可以使list
>>> classmate
['Computer', 'Wh0am1', 'Linux', 'Windows', ['Hacker']]
>>> classmate.insert(1,a)
>>> classmate
['Computer', ['Hacker'], 'Wh0am1', 'Linux', 'Windows', ['Hacker']]
>>> a.append('Freebuf')
>>> classamte.insert(2,a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'classamte' is not defined
>>> classmate.insert(2,a)
>>> classmate
['Computer', ['Hacker', 'Freebuf'], ['Hacker', 'Freebuf'], 'Wh0am1', 'Linux', 'Windows', ['Hacker', 'Freebuf']]
>>> classmate[1][1]
'Freebuf'        #自己意会

tuple

不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。**

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

t = (1, 2)
t
(1, 2)
如果要定义一个空的tuple,可以写成():

t = ()
t
()
但是,要定义一个只有1个元素的tuple,如果你这么定义:

t = (1)
t
1
定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。
所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:

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

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])            #自己意会
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值