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
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) + '+'
print #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 ...
随机推荐
- Request、Request.Form、Request.QueryString 用法的区别
Request.Form:获取以POST方式提交的数据. Request.QueryString:获取地址栏参数(以GET方式提交的数据). Request:包含以上两种方式(优先获取GET方式提交的 ...
- Go语言相关图书推荐
Go语言编程 作 者 许式伟 等 著 出 版 社 人民邮电出版社 出版时间 2012-08-01 版 次 1 页 数 245 印刷时间 2012-08-01 开 ...
- excel导入数据到sqlserver
1.读取excel数据到dataset public static System.Data.DataSet ExcelSqlConnection(string filepath, string tab ...
- 30+简约时尚的Macbook贴花
当Macbooks Pro电脑在他们的设计之下仍然漂亮.独一无二时,我想说,他们已经成为相当的主流了.有时候如果你回忆过去的很美好的日子,当人们偷偷欣赏你的技术装备 的时候,大概是为你的外表增加亮点的 ...
- 使用Java进行MD5加密
使用Java自带的MessageDigest类可以轻松实现MD5加密,只不过加密后得到的是byte数组,我们需要将其转换为16进制的字符. 代码如下: package com.stepsoft.tes ...
- Command Line Tools uninstall
sudo rm -rf /Library/Developer/CommandLineTools
- mysql基础知识(4)--修改
修改表: 一般概述 通常,创建一个表,能搞定(做到)的事情,修改表也能做到.大体来说,就可以做到: 增删改字段: 增:alter table 表名 add [column] 字段名 字段类 ...
- 为什么在Spring的配置里,最好不要配置xsd文件的版本号
为什么dubbo启动没有问题? 原文链接:http://www.tuicool.com/articles/YRn67zM 这篇blog源于一个疑问: 我们公司使了阿里的dubbo,但是阿里的开源网站h ...
- Hibernate理论
1.什么是Hibernate? Hibernate是数据持久层的一个轻量级框架.数据持久层的框架有很多比如:iBATIS,myBatis,Nhibernate,Siena等等.并且Hibernate是 ...
- LabView中,下拉列表和枚举有什么区别?
枚举变量只能针对无符号整型数据U32,U16,U8; 而下拉列表则可以包括扩展精度,双精度,单精度,64位.长.双字节.单字节整型以及各种无符号整型(如下图黑色部分). 下拉列表