马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 戴宇轩 于 2015-3-21 11:31 编辑
列表的所有除魔法方法外的函数有: ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
下面将逐一介绍它们:
1. append()
在列表的最后添加一个元素>>> test = []
>>> test
[]
>>> test.append(6)
>>> test
[6]
>>> test.append('I love FishC!')
>>> test
[6, 'I love FishC!']
2. clear()
在不改变内存中位置的情况下清空列表>>> raw = [1, 2, 3]
>>> same = raw
>>> raw
[1, 2, 3]
>>> same
[1, 2, 3]
>>> raw.clear()
>>> raw
[]
>>> same
[]
有人说: "何必那么复杂, 直接raw = []不就完事了吗?"
但是, 这是不同的, 测试:>>> raw = [1, 2, 3]
>>> same = raw
>>> raw
[1, 2, 3]
>>> same
[1, 2, 3]
>>> raw = []
>>> raw
[]
>>> same
[1, 2, 3]
>>> id(raw) == id(same) # 检测它们在内存中在不在同一个地址
>>> False
3. copy()
浅拷贝(拓展内容见>>>这里<<<)>>> raw = [1, 2, 3]
>>> same = raw
>>> different = raw.copy()
>>> raw
[1, 2, 3]
>>> same
[1, 2, 3]
>>> different
[1, 2, 3]
>>> raw.append(4)
>>> raw
[1, 2, 3, 4]
>>> same
[1, 2, 3, 4]
>>> different
[1, 2, 3]
>>> id(raw) == id(same)
True
>>> id(raw) == id(different)
False
4. count()
统计某一个元素在列表中的个数>>> test = [1, 1, 2, 3, 1, 2]
>>> test.count(1)
3
>>> test.count(2)
2
>>> test.count(3)
1
5. extend()
将一个可迭代对象的每一项添加到列表的最后>>> test = [1, 2, 3]
>>> test
[1, 2, 3]
>>> test.extend([11, 22, 33])
>>> test
[1, 2, 3, 11, 22, 33]
6. index()
返回某个元素在列表中的下标>>> test = [3, 8, 4, 2, 1]
>>> test
[3, 8, 4, 2, 1]
>>> test.index(2)
3
>>> test.index(8)
1
>>> test.index(4)
2
7. insert()
将某个元素插在列表的某个位置
形式: ???.insert(位置, 元素)>>> test = [1, 1, 2, 3, 5, 8]
>>> test
[1, 1, 2, 3, 5, 8]
>>> test.insert(3, 10)
>>> test
[1, 1, 2, 10, 3, 5, 8]
>>> test.insert(5, 100)
>>> test
[1, 1, 2, 10, 3, 100, 5, 8]
8. pop()
删除列表中指定位置的元素并返回, 默认位置为-1(最后)>>> test = [1, 1, 9, 3, 6, 8]
>>> test
[1, 1, 9, 3, 6, 8]
>>> test.pop()
8
>>> test
[1, 1, 9, 3, 6]
>>> test.pop(2)
9
>>> test
[1, 1, 3, 6]
9. remove()
移除列表中第一个指定的元素>>> test = [1, 1, 2, 3, 4, 3]
>>> test
[1, 1, 2, 3, 4, 3]
>>> test.remove(1)
>>> test
[1, 2, 3, 4, 3]
>>> test.remove(3)
>>> test
[1, 2, 4, 3]
10. reverse()
在不改变内存中位置的情况下反转列表>>> test = [1, 1, 2, 3, 5, 8]
>>> test
[1, 1, 2, 3, 5, 8]
>>> test.reverse()
>>> test
[8, 5, 3, 2, 1, 1]
11. sort()
给列表排序, 可选参数: reverse(从大到小), key(为列表中每一个值进行key的计算, 按返回值大小排序>>> test1 = [8, 3, -9, 2, 5, 3]
>>> test1
[8, 3, -9, 2, 5, 3]
>>> test1.sort()
>>> test1
[-9, 2, 3, 3, 5, 8]
>>> test1.sort(reverse = True)
>>> test1
[8, 5, 3, 3 2, -9]
>>> test2 = ['z', 'abcde', 'cde']
>>> test2
['z', 'abc', 'cdeeee']
>>> test2.sort() # 默认按ASCII值大小排序
>>> test2
['abc', 'cdeeee', 'z']
>>> test2.sort(key = len) # 要求按长度排序
>>> test2
['z', 'abc', 'cdeeee']
|