第五篇:list

这一篇主要讲list。下一篇讲dictionary。

这两个数据类型在python中被频繁使用。

 

1.list概况

list故名思义,提供一个动态的列表容器,相对于其它语言,python中的list非常强大,它可以容纳不同的数据类型,嵌套list等。

>>> [1, [1, 2], [1, 2, [3, 4]], 'hello', {'这也行?'}]
[1, [1, 2], [1, 2, [3, 4]], 'hello', set(['\xd5\xe2\xd2\xb2\xd0\xd0?'])]

对于嵌套的list,可以通过多维下标访问:

>>> al = [1, [1, 2], [1, 2, [3, 4]], 'hello', {'这也行?'}]
>>> al[2][2][0]
3
>>> al[4]
set(['\xd5\xe2\xd2\xb2\xd0\xd0?'])


这样一来list就可以当作矩阵来用啦:

>>> A = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
>>> A
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
>>> [tmp[1] for tmp in A]
[2, 3, 4]

 

2.list方法

可以通过dir()方法查看list对象拥有的方法。list的常用方法如下:

>>> l1 = [1, 2]
>>> l2 = [9, 10]
>>> l3 =['hello']
>>> l1+l2 #加扩展
[1, 2, 9, 10]
>>> l2*3 #乘扩展
[9, 10, 9, 10, 9, 10]
>>> for x in l2: #遍历
	print(x)

	
9
10
>>> 3 in l2 #判断是否存在
False
>>> 9 in l2
True
>>> l2.append(11) #尾部添加元素
>>> l2
[9, 10, 11]
>>> l2.extend(l1) #尾部扩展list
>>> l2
[9, 10, 11, 1, 2]
>>> l2.extend([2, 3])
>>> l2
[9, 10, 11, 1, 2, 2, 3]
>>> l2.insert(2, 5) #指定位置插入
>>> l2
[9, 10, 5, 11, 1, 2, 2, 3]
>>> l2.insert(0, 2)
>>> l2
[2, 9, 10, 5, 11, 1, 2, 2, 3]
>>> l2.index(0) #没有这个元素

Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    l2.index(0)
ValueError: 0 is not in list
>>> l2.index(2) #返回元素第一个位置
0
>>> l2.sort() #由大到小排序
>>> l2
[1, 2, 2, 2, 3, 5, 9, 10, 11]
>>> l2.reverse() #反转
>>> l2
[11, 10, 9, 5, 3, 2, 2, 2, 1]
>>> del l2[0] #删除指定位置元素
>>> l2
[10, 9, 5, 3, 2, 2, 2, 1]
>>> del l2[0:2]
>>> l2
[5, 3, 2, 2, 2, 1]
>>> l2.pop()
1
>>> l2
[5, 3, 2, 2, 2]
>>> l2.remove(2)
>>> l2
[5, 3, 2, 2]
>>> l2[2:] = []
>>> l2
[5, 3]
>>> l2[1:2] = [2, 3, 4]
>>> l2
[5, 2, 3, 4]
>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]
>>> range(10) #index生成器
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


3.借助循环操作list的技巧

>>> x = ['hello', 'spam', 'SPAM']
>>> [i*3 for i in x]
['hellohellohello', 'spamspamspam', 'SPAMSPAMSPAM']


4.list转换

list与string互转:

>>> str = 'hello'
>>> list(str)
['h', 'e', 'l', 'l', 'o']
>>> list = ['h', 'e', 'l', 'l', 'o']
>>> str = ''.join(list)
>>> str
'hello'

通过list函数,可以实现str到list的转换,不过转换强制以一个字符为单位。

通过string的join函数,可以实现list到string的转换。但是要注意,此时list不能有非字符的元素,如list=[1, 2] 就不能被转换。

 

list与tuple互转:

>>> list((1, 2, 3))
[1, 2, 3]
>>> tuple([1, 2, 3])
(1, 2, 3)


list与dictionary互转:

>>> ll = [('good', 1), ('bad', 2)]
>>> dict(ll) #list转dictionary
{'bad': 2, 'good': 1}
>>> dic = dict(ll)
>>> list(dic) #dictionary转list
['bad', 'good']

 

end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值