1、创建list
>>> a=["python",25,89.9]
>>> a
["python",25,89.9]
2、list的索引方法
用索引来访问列表中的元素。
>>> a=["python",25,89.9]
>>> a[0]
'python'
>>> a[1]
25
>>> a[2]
89.9
>>> a[-1]
89.9
#获取元素在list中的索引
>>> a.index(25)
1
>>> a.index(89.9)
2
>>> a.index("python")
0
>>> a.index("blog")
Traceback (most recent call last):
File "
a.index("blog")
ValueError: 'blog' is not in lis
3、list切片(slice([start],stop[,step]))
创建一个新列表,它是原列表的子集。
>>> a=["python",25,89.9]
>>> a[0:2]
['python',25]
>>> a[:1]
['python',25]
>>> a[0:]
["python",25,89.9]
>>> lst= [1,2,3,4,5,6]
>>> lst[::-1]
[6, 5, 4, 3, 2, 1]
>>> lst[0:4]
[1, 2, 3, 4]
>>> lst[0:4:1]
[1, 2, 3, 4]
>>> lst[0:4:2]
[1, 3]
>>> lst[4:1:-1]
[5, 4, 3]
>>> list(reversed(lst))
[6, 5, 4, 3, 2, 1]
>>>len(lst)
6
>>> lst + a
[6, 5, 4, 3, 2, 1,"python", 25, 89.9]
>>> a * 3
["python", 25, 89.9, "python", 25, 89.9, "python", 25, 89.9]
>>> max(lst)
6
>>> min(lst)
1
>>> max(a)
'python'
>>> min(a)
25
>>> cmp(a,lst)
1
4、append(object)
添加一个元素到list末尾。
>>> a = [1,2]
>>> a.append(100)
>>> a
[1,2,100]
>>> a.append("python")
>>> a
[1,2,100,'python']
>>> a.append(["google","facebook"])
>>> a
[1,2,100,'python',['google','facebook']]
>>> b = [1]
>>> id(b)
46824863
>>> b.append(5)
>>>b
[1, 5]
>>> id(b)
46824863
5、extend(iterable)
添加多个元素到list, extend
能够接受的参数必须是一个可迭代对象。
>>>a = [1, 2, 3]
>>>b = [4, 5, 6]
>>>a.extend(b)
>>>a
>>>[1, 2, 3, 4, 5, 6]
>>>a.extend(3)
E:\01_workSpace\02_programme_language\03_python\OOP>pythonappend_extend.py
Traceback (mostrecent call last):
File "append_extend.py", line 6, in
l a.extend(3)
TypeError: 'int'object is not iterable
--从上面的提示可以看出,extend能够接受的参数必须是一个可迭代对象。
>>>a.extend("python")
>>>a
[1, 2, 3, 4, 5, 6, 'p', 'y', 't', 'h', 'o', 'n']
#判断对象是否是可迭代的
>>> hasattr(a,'__iter__')
True
>>> hasattr("python",'__iter__')
False
>>> hasattr(5,'__iter__')
False
6、count(...) integer
方法返回指定的元素在list中出现的次数。
>>> a = [1,1,1,2,2,1]
>>> a.count(1)
4
>>> a.count(2)
2
>>> a.count("a")
0
7、index(value, [start, [stop]]) integer
得到元素第一次在list中的索引。
>>> a = [1,1,1,2,2,1]
>>> a.index(1)
0
>>> a.index(2)
3
8、insert(index, object)
插一个元素在index索引前。
>>> a = ["python", "web"]
>>> a.insert(1,"qwer")
>>> a
['python', 'qwer', 'web']
>>> a.insert(0,26066913)
>>> a
[26066913,'python', 'qwer', 'web']
9、pop([index]) item
删除指定索引元素并且返回该元素,如不传index
索引则默认是删除最后一个元素。
>>> a = ["wiki","twitter","google","facebook"]
>>> a.pop(1)
'wiki'
>>> a
['twitter','google','facebook']
>>> a.pop()
'facebook'
>>> a
['twitter','google']
10、remove(value)
删除每一次出现的元素。
>>> a = ['twitter','twitter','google','facebook']
>>> a.remove("twitter")
>>> a
['twitter','google','facebook']
11、reverse()
方法返回倒序的list
。
>>> a=[1,2,3,4]
>>> a.reverse()
>>> a
[4, 3, 2, 1]
12、sort(...)
将list中元素排序。
>>> a = [5, 3, 9, 2]
>>> a.sort()
>>> a
[2, 3, 5, 9]