Python中的基本list操作

List是python中的基本数据结构之一,和Java中的ArrayList有些类似,支持动态的元素的增加。list还支持不同类型的元素在一个列表中,List is an Object。

最基本的创建一个列表的方法

myList = ['a','b','c']

在python中list也是对象,所以他也有方法和属性,在ptython解释器中 使用help(list)可以查看其文档,部分开放方法如下:

在接下来的代码中,将使用这些方法:

# coding=utf-8

# Filename : list.py
# Date: 2012 11 20



# 创建一个list方式
heatList = ['wade','james','bosh','haslem']
tableList = list('123')  #list方法接受一个iterable的参数

print 'Miami heat has ',len(heatList),' NBA Stars , they are:'

#遍历list中的元素
for player in heatList:
    print player,


#向list添加元素
heatList.append('allen') #方式一:向list结尾添加 参数object
print '\nAfter allen join the team ,they are: '
print heatList

heatList.insert(4,'lewis') #方式二:插入一个元素 参数一:index位置 参数二:object
print 'After lewis join the team, they are:'
print heatList

heatList.extend(tableList)  #方式三:扩展列表,参数:iterable参数
print 'After extend a table list,now they are :'
print heatList

#从list删除元素
heatList.remove('1')   #删除方式一:参数object 如有重复元素,只会删除最靠前的
print" Remove '1' ..now '1' is gone\n",heatList

heatList.pop()   #删除方式二:pop 可选参数index删除指定位置的元素 默认为最后一个元素
print "Pop the last element '3'\n",heatList

del heatList[6] #删除方式三:可以删除制定元素或者列表切片
print "del '3' at the index 6\n",heatList


#逻辑判断

#统计方法 count 参数:具体元素的值
print 'james apears ',heatList.count('wade'),' times'

#in 和 not in 
print 'wade in list ? ',('wade' in heatList)
print 'wade not in list ? ',('wade' not in heatList)

#定位 index方法:参数:具体元素的值 可选参数:切片范围
print 'allen in the list ? ',heatList.index('allen')
#下一行代码会报错,因为allen不在前三名里
#print 'allen in the fisrt 3 player ? ',heatList.index('allen',0,3)

#排序和反转代码
print 'When the list is reversed : '
heatList.reverse()
print heatList

print 'When the list is sorted: '
heatList.sort() #sort有三个默认参数 cmp=None,key=None,reverse=False 因此可以制定排序参数以后再讲
print heatList

#list 的分片[start:end] 分片中不包含end位置的元素
print 'elements from 2nd to 3rd ' , heatList[1:3]
以上都是list最基本的操作,当然还包括和其他数据结构之间的转操作,注:python sort用的是稳定的排序算法

作者: leeon
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,否则保留追究法律责任的权利.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值