python学习笔记(列表、元组)

列表:列表是可变 --可以改变列表的内容,并且列表有很多有用的、专门的方法

list:

list函数可以将一个字符串分成列表,list函数适用于所有类型的序列,不只是字符串

>>> list('hello,world')
['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd']

join可以将由一个字符组成的列表转换成字符串

>>> s=''
>>> li=['h','e','l','l','o']
>>> h=s.join(li)
>>> print h
hello
>>> a

改变列表,元素赋值,不能为一个位置不存在的元素赋值,如列表长度为2,就不能为索引为3的元素赋值

>>> x=[1,2,3,4,5]
>>> x[1]=6
>>> x
[1, 6, 3, 4, 5]
删除元素

>>> x=[1,2,3,4,5]
>>> del x[2]
>>> x
[1, 2, 4, 5]

分片赋值

>>> name=list('perl')
>>> name
['p', 'e', 'r', 'l']
>>> name[1:]=list('ython')
>>> name
['p', 'y', 't', 'h', 'o', 'n']

>>> number=[1,5]
>>> number[1:1]=[2,3,4]
>>> number
[1, 2, 3, 4, 5]
>>> number[1:4]=[]
>>> number
[1, 5]

列表方法

append

append用于在列表末尾追加新的对象

>>> numbers=[1,2,3]
>>> numbers.append(4)
>>> numbers
[1, 2, 3, 4]

count

count方法统计某个元素在列表中出现的次数

>>> x=[1,[1,2],2,3,[1,2],[1,[1,2]],5]
>>> x.count(1)
1
>>> x.count([1,2])
2

extend

extend方法可以用于在列表末尾一次性追加另一个序列中的多个值,用新列表扩展原有列表

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]

index

index方法用于从列表中找出某个值第一个匹配项的索引位置

>>> x=[1,2,3,4,5]
>>> x.index(3)
2

insert

insert用于将对象插入到列表中

>>> x=[1,2,3,4,5,6]
>>> x.insert(3,'four')
>>> x
[1, 2, 3, 'four', 4, 5, 6]

pop

pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值

>>> x=[1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

remove

remove方法用于移除列表中某个值的第一个匹配项

>>> x=['to','be','or','not','to','be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']

reverse

reverse方法用于将列表中的元素反向存放

>>> x=['to','be','or','not','to','be']
>>> x.reverse()
>>> x
['be', 'to', 'not', 'or', 'be', 'to']
>>>

sort

sort方法用于在原位置对列表 进行排序

>>> x=[2,1,5,4,9]
>>> x.sort()
>>> x
[1, 2, 4, 5, 9]

元组

元组与列表一样,也是一种序列。唯一的不同是元组不能改变。创建元组的语法很简单:如果你用逗号分割了一些值,那么你就自动创建了元组。

>>> 1,2,3
(1, 2, 3)
>>> (1,2,3) # 用括号表示元组
(1, 2, 3)
>>> () # 空元组
()

如何实现包含一个值的元组呢?方法有点奇特----必须加逗号,即使只有一个值:

>>> 42,
(42,)
>>> (42,)
(42,)
>>> 3 * (20+1)

63
>>> 3 * (20+1,)
(21, 21, 21)

tuple

tuple函数的功能和list函数基本一样,以一个序列作为参数并把它转换成元组。如果该参数就是元组,则该参数就会被原样返回

>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')

>>> tuple((1,2,3))
(1, 2, 3)

 (参考书籍:python基础教程)

posted @ 2015-07-28 14:00  whats  阅读(143)  评论(0编辑  收藏  举报