Python基础教程之第2章 列表和元组
- D:\>python
- Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
- Type "help", "copyright", "credits" or "license" for more information.
- #2.1序列概览
- >>> edward=['Edward Gumby', 42]
- >>> john=['John Smith',50]
- >>> database=[edward,john]
- >>> database
- [['Edward Gumby', 42], ['John Smith', 50]]
- #2.2通用序列操作
- #2.2.1索引
- #代码清单2-1索引演示样例
- >>> greeting='Hello'
- >>> greeting[0]
- 'H'
- >>> greeting[-1]
- 'o'
- >>> 'hello'[1]
- 'e'
- >>> fourth=raw_input('Year: ')[3]
- Year: 2005
- >>> fourth
- '5'
- #2.2.2分片/切片
- >>> tag = '<a href="http://www.python.org">Python web site</a>'
- >>> tag[9:30]
- 'http://www.python.org'
- >>> tag[32:-4]
- 'Python web site'
- >>> numbers = [1,2,3,4,5,6,7,8,9,10]
- >>> numbers[3,6]
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: list indices must be integers, not tuple
- >>> numbers[3:6]
- [4, 5, 6]
- >>> numbers[0:1]
- [1]
- # 1. 优雅的捷径
- >>> numbers[7:10]
- [8, 9, 10]
- >>> numbers[-3:-1]
- [8, 9]
- >>> numbers[-3:0]
- []
- >>> numbers[-3:]
- [8, 9, 10]
- >>> numbers[:3]
- [1, 2, 3]
- >>> numbers[:]
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- #代码清单2-2 分片演示样例
- #2.更大的步长
- >>> numbers[0:10:1]
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- >>> numbers[0:10:2]
- [1, 3, 5, 7, 9]
- >>> numbers[3:6:3]
- [4]
- >>> numbers[::4]
- [1, 5, 9]
- >>> numbers[8:3:-1]
- [9, 8, 7, 6, 5]
- >>> numbers[8:3:1]
- []
- >>> numbers[8:3:+1]
- []
- >>> numbers[10:0:-2]
- [10, 8, 6, 4, 2]
- >>> numbers[9:0:-2]
- [10, 8, 6, 4, 2]
- >>> numbers[11:0:-2]
- [10, 8, 6, 4, 2]
- >>> numbers[0:10:-2]
- []
- >>> numbers[::-2]
- [10, 8, 6, 4, 2]
- >>> numbers[5::-2]
- [6, 4, 2]
- >>> numbers[0:5:-2]
- []
- >>> numbers[0:5:2]
- [1, 3, 5]
- >>> numbers[:5:-2]
- [10, 8]
- #2.2.3序列相加
- >>> [1,2,3]+[4,5,6]
- [1, 2, 3, 4, 5, 6]
- >>> 'Hello, ' + 'world'
- 'Hello, world'
- >>> [1,2,3] + 'world!'
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: can only concatenate list (not "str") to list
- #2.2.4乘法
- >>> 'python' * 5
- 'pythonpythonpythonpythonpython'
- >>> 5 * 'python'
- 'pythonpythonpythonpythonpython'
- >>> [42] * 10
- [42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
- # None, 空列表和初始化
- #代码清单2-3 序列(字符串)乘法演示样例
- >>> [0] * 10
- [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
- >>> sequence = [None] * 10
- >>> sequence
- [None, None, None, None, None, None, None, None, None, None]
- #2.2.5 成员资格
- #代码清单2-4 序列成员资格演示样例
- >>> permissions = 'rw'
- >>> 'w' in permissions
- True
- >>> 'x' in permissions
- False
- >>> users = ['mlh','foo','bar']
- >>> raw_input('Enter your user name: ') in users
- Enter your user name: mlh
- True
- >>> subject = '$$$ Get rich now! $$$'
- >>> '$$$' in subject
- True
- >>> 'P' in 'Python'
- True
- #2.2.6 长度, 最小值和最大值
- >>> numbers=[100,34,678]
- >>> len(numbers)
- 3
- >>> max(numbers)
- 678
- >>> min(numbers)
- 34
- >>> max(2,3)
- 3
- >>> min(9,3,2,5)
- 2
- #2.3 列表: Python的"苦力"
- # 列表不同于元组和字符串的地方:列表是可变的(mutable)
- >>> list('Hello')
- ['H', 'e', 'l', 'l', 'o']
- >>> somelist=list('Hello')
- >>> ''.join(somelist)
- 'Hello'
- #2.3.2主要的列表操作
- #1.改变列表:元素赋值
- >>> x=[1,1,1]
- >>> x[1]=2
- >>> x
- [1, 2, 1]
- #2.删除元素
- >>> names=['Alice','Beth','Cecil','Dee-Dee','Earl']
- >>> del names[2]
- >>> names
- ['Alice', 'Beth', 'Dee-Dee', 'Earl']
- #3.分片赋值/切片赋值
- >>> name=list('Perl')
- >>> name
- ['P', 'e', 'r', 'l']
- >>> name[2:]=list('ar')
- >>> name
- ['P', 'e', 'a', 'r']
- >>> name = list('Perl')
- >>> name[1:]=list('ython')
- >>> name
- ['P', 'y', 't', 'h', 'o', 'n']
- >>> numbers=[1,5]
- >>> numbers[1:1] = [2,3,5]
- >>> numbers
- [1, 2, 3, 5, 5]
- >>> numbers
- [1, 2, 3, 5, 5]
- >>> numbers[1:4] = []
- >>> numbers
- [1, 5]
- #2.3.3 列表的方法
- #1.append
- >>> lst = [1,2,3]
- >>> lst.append(4)
- >>> lst
- [1, 2, 3, 4]
- >>> ['to','be','or','not','to','be'].count('to')
- 2
- #2.count
- >>> x = [[1,2],1,1,[2,1,[1,2]]]
- >>> x.count(1)
- 2
- >>> x.count([1,2])
- 1
- #3.extend
- >>> a = [1,2,3]
- >>> b = [4,5,6]
- >>> a.extend(b)
- >>> a
- [1, 2, 3, 4, 5, 6]
- >>> b
- [4, 5, 6]
- >>> a = [1,2,3]
- >>> b = [4,5,6]
- >>> a + b
- [1, 2, 3, 4, 5, 6]
- >>> a
- [1, 2, 3]
- >>> a = a + b
- >>> a
- [1, 2, 3, 4, 5, 6]
- >>> a = [1,2,3]
- >>> b = [4,5,6]
- >>> a[len(a):]=b
- >>> a
- [1, 2, 3, 4, 5, 6]
- #4.index
- >>> knights = ['We','are','the','knights','who','say','ni']
- >>> knights.index('who')
- 4
- >>> knights.index('herring')
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: 'herring' is not in list
- >>> knights[4]
- 'who'
- #5.insert
- >>> numbers = [1,2,3,5,6,7]
- >>> numbers.insert(3,'four')
- >>> numbers
- [1, 2, 3, 'four', 5, 6, 7]
- >>> numbers = [1,2,3,5,6,7]
- >>> numbers[3:3] = ['four']
- >>> numbers
- [1, 2, 3, 'four', 5, 6, 7]
- #6.pop
- >>> x = [1,2,3]
- >>> x.pop()
- 3
- >>> x
- [1, 2]
- >>> x.pop(0)
- 1
- >>> x
- [2]
- >>> x = [1,2,3]
- >>> x.append(x.pop())
- >>> x
- [1, 2, 3]
- #7.remove
- >>> x=['to','be','or','not','to','be']
- >>> x.remove('be')
- >>> x
- ['to', 'or', 'not', 'to', 'be']
- >>> x.remove('bee')
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: list.remove(x): x not in list
- >>>
- Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
- Type "copyright", "credits" or "license()" for more information.
- #8.reverse
- >>> x = [1,2,3]
- >>> x.reverse()
- >>> x
- [3, 2, 1]
- >>> x = [1,2,3]
- >>> type(reversed(x))
- <type 'listreverseiterator'>
- >>> list(reversed(x))
- [3, 2, 1]
- #9.sort
- >>> x = [4,6,2,1,7,9]
- >>> x
- [4, 6, 2, 1, 7, 9]
- >>> x.sort()
- >>> x
- [1, 2, 4, 6, 7, 9]
- >>> x = [4,6,2,1,7,9]
- >>> y = x.sort() # Don't do this!
- >>> print y
- None
- >>> x = [4,6,2,1,7,9]
- >>> y = x
- >>> y
- [4, 6, 2, 1, 7, 9]
- >>> y = x[:]
- >>> y
- [4, 6, 2, 1, 7, 9]
- >>> y.sort()
- >>> x
- [4, 6, 2, 1, 7, 9]
- >>> y
- [1, 2, 4, 6, 7, 9]
- >>> x
- [4, 6, 2, 1, 7, 9]
- >>> y=x
- >>> x
- [4, 6, 2, 1, 7, 9]
- >>> y
- [4, 6, 2, 1, 7, 9]
- >>> y.sort()
- >>> x
- [1, 2, 4, 6, 7, 9]
- >>> y
- [1, 2, 4, 6, 7, 9]
- >>> x=[4,6,2,1,7,9]
- >>> y = sorted(x)
- >>> x
- [4, 6, 2, 1, 7, 9]
- >>> y
- [1, 2, 4, 6, 7, 9]
- >>> sorted('Python')
- ['P', 'h', 'n', 'o', 't', 'y']
- #10.高级排序
- >>> cmp(42,32)
- 1
- >>> cmp(99,100)
- -1
- >>> cmp(10,10)
- 0
- >>> numbers = [5,2,9,7]
- >>> numbers.sort(cmp)
- >>> numbers
- [2, 5, 7, 9]
- >>> x = ['aardvark','abalone','acme','add','aerate']
- >>> x.sort(key=len)
- >>> x
- ['add', 'acme', 'aerate', 'abalone', 'aardvark']
- >>> x = [4,6,2,1,7,9]
- >>> x.sort(reverse=True)
- >>> x
- [9, 7, 6, 4, 2, 1]
- #2.4 元组:不可变序列
- >>> 1,2,3
- (1, 2, 3)
- >>> (1,2,3)
- (1, 2, 3)
- >>> ()
- ()
- >>> 42
- 42
- >>> 42,
- (42,)
- >>> (42,)
- (42,)
- >>> 3*(40+2)
- 126
- >>> 3*(40+2,)
- (42, 42, 42)
- #2.4.1 tuple函数
- >>> tuple([1,2,3])
- (1, 2, 3)
- >>> tuple('abc')
- ('a', 'b', 'c')
- >>> tuple((1,2,3))
- (1, 2, 3)
- #2.4.2 基本元组操作
- >>> x = 1,2,3
- >>> x[1]
- 2
- >>> x[0:2]
- (1, 2)
- >>>
- #2.4.3 那么,意义何在
- #1.元组能够在映射(和集合的成员)中当做键使用,而列表则不行
- #2.元组作为非常多内建函数和方法的返回值存在,也就是说你必须对元组进行处理.
- #2.5小结
- #序列. 序列是一种数据结构, 它包括的元素都进行了编号(从0開始). 典型的序列包括列表, 字符串和元组. 当中, 列表是可变的(能够进行改动),而元组和字符串是不可变的
- #(一旦创建了就是固定的). 通过分片操作能够訪问序列的一部分,当中分片须要两个索引號来指出分片的起始和结束位置. 要想改变列表, 则要对对应的位置进行赋值,或
- #使用赋值语句重写整个分片.
- #成员资格 in操作符能够检查一个值是否存在于序列(或其它的容器)中. 对字符串使用in操作符是一个特例--它能够查找子字符串.
- #方法. 一些内建类型(比如列表和字符串, 元组则不在当中)具有非常多实用的方法. 这些方法有些像函数--只是它们与特定值联系得更密切.方法是面向对象编程的一个重要
- #概念.
- # 本章的新函数
- #cmp(x,y) 比較两个值
- #len(seq) 返回序列的长度
- #list(seq) 把序列转换成列表
- #max(args) 返回序列或參数集合中的最大值
- #min(args) 返回序列或參数集合中的最小值
- #reversed(seq) 对序列进行反向迭代
- #sorted(seq) 返回已排序的包括seq全部元素的列表
- #tuple(seq) 把序列转换为元组
- #2.5.2 接下来学什么
- # 序列已经介绍完了, 下一章会继续介绍由字符组成的序列,即字符串.
代码清单2-1索引演示样例
- #!/usr/bin/env python
- #encoding=utf-8
- months = [
- 'January',
- 'February',
- 'March',
- 'April',
- 'May',
- 'June',
- 'July',
- 'August',
- 'September',
- 'October',
- 'November',
- 'December'
- ]
- # 以1-31的数字作为结尾的列表
- endings = ['st','nd','rd'] + 17 * ['th'] \
- + ['st','nd','rd'] + 7 * ['th'] \
- + ['st']
- year = raw_input('Year: ')
- month = raw_input('Month(1-12): ')
- day = raw_input('Day(1-31): ')
- month_number = int(month)
- day_number = int(day)
- #记得要将月份和天数减1,以获得正确的索引
- month_name = months[month_number-1]
- ordinal = day + endings[day_number-1]
- print month_name + ' ' + ordinal + ', ' + year
- #python e2-1.py
- #Year: 1981
- #Month(1-12): 1
- #Day(1-31): 1
- #January 1st, 1981
代码清单2-2 分片演示样例
- #encoding=utf8
- #对http://www.something.com形式的URL进行切割
- url = raw_input('Please enter the URL: ')
- domain = url[11:-4]
- print "Domain name: " + domain
- #python e2-2.py
- #Please enter the URL: http://www.python.org
- #Domain name: python
代码清单2-3 序列(字符串)乘法演示样例
- #encoding=utf-8
- #以正确的宽度在居中的"盒子"内打印一个句子
- #注意,整数除法运算(//)仅仅能用在Python2.2以及兴许版本号,在之前的版本号中,仅仅使用普通除法(/)
- sentence = raw_input("Sentence: ")
- screen_width = 80
- text_width = len(sentence)
- box_width = text_width + 6
- left_margin = (screen_width - box_width) // 2
- print ' ' * left_margin + '+' + '-' * (box_width-2) + '+'
- print ' ' * left_margin + '|' + ' ' * (box_width-2) + '|'
- print ' ' * left_margin + '|' + ' ' * 2 + sentence + ' ' * 2 + '|'
- print ' ' * left_margin + '|' + ' ' * (box_width-2) + '|'
- print ' ' * left_margin + '+' + '-' * (box_width-2) + '+'
- #python e2-3.py
- #Sentence: He's a very naughty boy!
- #
- # +----------------------------+
- # | |
- # | He's a very naughty boy! |
- # | |
- # +----------------------------+
- #
代码清单2-4 序列成员资格演示样例
- #encoding=utf-8
- database = [
- ['albert','1234'],
- ['dilbert','4242'],
- ['smith','7524'],
- ['jones','9843'],
- ['jonathan','6400']
- ]
- username = raw_input('User name: ')
- pin = raw_input('PIN code: ')
- if [username, pin] in database: print 'Access granted'
- #python e2-4.py
- #User name: jonathan
- #PIN code: 6400
- #Access granted
Python基础教程之第2章 列表和元组的更多相关文章
- Python基础教程之第5章 条件, 循环和其它语句
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 #Chapter 5 条件, 循环 ...
- Python基础教程之第3章 使用字符串
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyri ...
- Python基础教程之第1章 基础知识
#1.1 安装Python #1.1.1 Windows #1.1.2 Linux和UNIX #1.1.3 Macintosh #1.1.4 其它公布版 #1.1.5 时常关注.保持更新 #1.2 交 ...
- Python基础教程之List对象 转
Python基础教程之List对象 时间:2014-01-19 来源:服务器之家 投稿:root 1.PyListObject对象typedef struct { PyObjec ...
- Python基础教程之udp和tcp协议介绍
Python基础教程之udp和tcp协议介绍 UDP介绍 UDP --- 用户数据报协议,是一个无连接的简单的面向数据报的运输层协议.UDP不提供可靠性,它只是把应用程序传给IP层的数据报发送出去,但 ...
- python基础之数字、字符串、列表、元组、字典
Python基础二: 1.运算符: 判断某个东西是否在某个东西里面包含: in 为真 not in 为假 (1).算术运算符: 运算符 描述 实例 + 加 表示两个对象相加 a + b输出结果3 ...
- python 基础学习笔记(3)--列表与元组
**本次笔记主要内容为 列表,元组主要的功能和特性** **1.列表**: 学习过c语言的同学应该知道,c语言有数组这一功能,就是将数据类型相同的元素放在一起.由于python的变量没有数据类型,也就 ...
- Python基础灬序列(字符串、列表、元组)
序列 序列是指它的成员都是有序排列,并且可以通过下标偏移量访问到它的一个或几个成员.序列包含字符串.列表.元组. 字符串 chinese_zodiac = '鼠牛虎兔龙蛇马羊猴鸡狗猪' print(c ...
- python基础教程之pymongo库
1. 引入 在这里我们来看一下Python3下MongoDB的存储操作,在本节开始之前请确保你已经安装好了MongoDB并启动了其服务,另外安装好了Python的PyMongo库. 1. 安装 pi ...
随机推荐
- SQL 教程学习进度备忘
书签:跳过:另外跳过的内容有待跟进 __________________ 学习资源:W3School. _________________ 跳过的内容: 1. “SQL select”底部的“ AD ...
- 【LeetCode】190 & 191 - Reverse Bits & Number of 1 Bits
190 - Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 432615 ...
- xcode XCTest录制后测试出错临时解决方法
Xcode 使用 XCTest 做自动化测试,录制后在run UITest 的时候总是莫名报错,后来在方法执行前添加sleep()后,没有再出现错误,可能是xcode的一处BUG.
- HDU-3872 Dragon Ball 线段树+DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3872 题意:有n个龙珠按顺序放在一列,每个龙珠有一个type和一个权值,要求你把这n个龙珠分成k个段, ...
- 【转】webgame前台开发总结--虽然是10年的文章,但是也有参考价值
一.webgame整个游戏流程: 1.预加载(打开游戏页面后,显示进度条,主要加载前期的登陆和创建角色资源,创建角色资源的加载可以放到进入创建角色界面的时候加载,因为玩家除了第一次进入游戏,其他时间基 ...
- tomcat 粗略笔记
GlobalNamingResources 存在于server.xml中,定义全局公共数据源,如果host中有大量引用相同的数据源,那么可以都配在这里 <GlobalNamingResource ...
- Jenkins+Gitlab搭建持续集成(CI)环境
利用Jenkins+Gitlab搭建持续集成(CI)环境 Permalink: 2013-09-08 22:04:00 by hyhx2008in intern tags: jenkins gitla ...
- CTE初识
微软从SQl2005起引入了CTE(Common Table Expression)以强化T-SQL.这是一个类似于非持久视图的好东西. 正常的SQL语句: select * from person. ...
- Thinkphp模板怎么使用自定义函数
内置模板引擎支持对模板变量使用函数,并支持多个函数同时使用. 注意:自定义函数要放在项目应用目录/common/common.php中. 这里是关键. 模板变量的函数调用格式:{$varname|fu ...
- Ehcache详细解读
[http://raychase.iteye.com/blog/1545906] Ehcache 是现在最流行的纯Java开源缓存框架. [通过编程方式使用EhCache ] //从class ...