Python list使用示例,pythonlist示例,#!/usr/bin/p
Python list使用示例,pythonlist示例,#!/usr/bin/p
#!/usr/bin/python# 定义python list,list中可以有不同类型的数据fred = [ 'The', 'answer', 'to', 'your', 'question', 'is', 24 ]print 'A:', fred# 通过[x]可以获得list x位置的元素print 'B:', fred[0], fred[2], fred[6], fred[-1], fred[-4]# 通过 list[x:y]的方式可以获得list的一部分print 'C:', fred[2:5], fred[-6:-3], fred[4:5], fred[3:3]# 可以通过下面方式给list指定位置的元素赋值fred[1] = 'response'fred[-1] = fred[-1] + 200fred[-3] = 'query'print 'D:', fred# 同样可以通过slice的方式给list的一部分赋值fred[0:2] = [ 'An', 'unlikely', 'answer' ]fred[-1:-1] = [ 'a', 'conservative' ]print 'E:', fred# list中可以包含listmike = [ 3, 4, ['and', 'also', 'a'], 52]print 'F:', mikemike[0] = [2, '+', 1]mike[2] = 11print 'G:', mikefred[1:3] = [fred[1:3]]fred[-1:] = [mike]print 'H:', fredprint 'Fred has', len(fred), 'entries.'
下面代码演示list相关操作:
#!/usr/bin/pythonfred = [ 'Alice', 'goes', 'to', 'market' ]print 'A:', fred#extend方法扩展listfred.extend([ 'with', 'Mike' ])print 'B:', fred#pop方法返回list最后一个元素,并移除最后一个元素last = fred.pop()fred.append('Fred')print 'C:', fredprint 'So much for Mike.'print 'There are', len(fred), 'items in fred.'print 'The word market is located at position', fred.index('market')fred = [ 'On', 'Tuesday,' ] + fredprint 'D:', fred#reverse()方法反转listfred.reverse()print 'E:', fredfred.sort()print 'F:', fred
相关内容
- python if 语句,pythonif,#!/usr/bin/p
- python while语句,pythonwhile,python while
- Python使用cx_Oracle将oracle数据表中的数据导出成csv,cx_
- python正则re模块学习笔记,pythonre学习笔记,python正则r
- Python 初学教程 for语句,python初学for语句,python for 语
- Python 处理mp3文件中的图片和歌词信息,,一些MP3播放器
- Python使用PyMedia播放mp3,wave等文件,pythonpymedia,Pymedia 是
- Python合并文本文件代码,,# coding gbk
- python 初学教程 做比较和逻辑运算,python初学,python 做比
- python编写web service,pythonwebservice,以前都是用C#写webs
评论关闭