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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值