Python学习笔记——list的经常用法
python里list的经常用法都试用了一下,把功能和用法小结一下,这里不包含那些“__xxx__”形式的内置函数
#__author__ = 'hualong_zhang' # -*- coding:utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') init_list_1 = [1, 4, 9, 'cat', 'dog', 'dog', 'bird', ['fish']] init_list_2 = [1, 4, 9] print 'the origin list 1 and 2:\n', init_list_1, '\n', init_list_2 init_list_1.append(16) # 尾加一个元素 print init_list_1 print init_list_1.count('dog') # 返回某元素出现个数 init_list_1.extend(init_list_2) # 尾加一个list print init_list_1 print init_list_1.index('cat') # 返回某元素位置 init_list_1.insert(3, 'bird') # 插入 print init_list_1 for i in range(4): init_list_1.pop() # 从后弹出 print init_list_1 init_list_1.remove('dog') # 移除 init_list_1.remove('dog') print init_list_1 init_list_1.reverse() # 反转函数 print init_list_1 print str(init_list_1)#转换为字符串,是给人看的那种 print repr(init_list_1)#抓换成能显示的东西,无论什么对象都行,不同于str() #sort方法的使用 list_for_sort = [1, 8, 2, 2, 2, 3, 3, 3, 3, 1, 7] print list_for_sort list_for_sort.sort()#光一个sort,简单排序 print list_for_sort list_for_sort.sort(reverse=True)#翻转,也就是逆序 print list_for_sort list_for_sort.sort(cmp, reverse=True)#用默认的cmp比較加逆序。也能够用于自己定义的cmp print list_for_sort #用sort的key list_for_sort_2 = [('dog', 7), ('cat', 6), ('bird', 3), ('human', 4), ('fish', 2)] print list_for_sort_2 list_for_sort_2.sort(key=lambda x: x[0])#按每一个元素第一项排序 print list_for_sort_2 list_for_sort_2.sort(key=lambda x: (x[1], x[0]))#比較优先级为先看第二项再看第一项 print list_for_sort_2 #再用cmp方式的第一项指标排序 list_for_sort_2.sort(cmp=lambda x,y:cmp(x[0],y[0]))
执行结果例如以下:
the origin list 1 and 2:
[1, 4, 9, 'cat', 'dog', 'dog', 'bird', ['fish']]
[1, 4, 9]
[1, 4, 9, 'cat', 'dog', 'dog', 'bird', ['fish'], 16]
2
[1, 4, 9, 'cat', 'dog', 'dog', 'bird', ['fish'], 16, 1, 4, 9]
3
[1, 4, 9, 'bird', 'cat', 'dog', 'dog', 'bird', ['fish'], 16, 1, 4, 9]
[1, 4, 9, 'bird', 'cat', 'dog', 'dog', 'bird', ['fish']]
[1, 4, 9, 'bird', 'cat', 'bird', ['fish']]
[['fish'], 'bird', 'cat', 'bird', 9, 4, 1]
[['fish'], 'bird', 'cat', 'bird', 9, 4, 1]
[['fish'], 'bird', 'cat', 'bird', 9, 4, 1]
[1, 8, 2, 2, 2, 3, 3, 3, 3, 1, 7]
[1, 1, 2, 2, 2, 3, 3, 3, 3, 7, 8]
[8, 7, 3, 3, 3, 3, 2, 2, 2, 1, 1]
[8, 7, 3, 3, 3, 3, 2, 2, 2, 1, 1]
[('dog', 7), ('cat', 6), ('bird', 3), ('human', 4), ('fish', 2)]
[('bird', 3), ('cat', 6), ('dog', 7), ('fish', 2), ('human', 4)]
[('fish', 2), ('bird', 3), ('human', 4), ('cat', 6), ('dog', 7)]
[('bird', 3), ('cat', 6), ('dog', 7), ('fish', 2), ('human', 4)]
Process finished with exit code 0