`

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基础教程学习笔记 第二章 列表和元组

    主要介绍了Python基础教程学习笔记 第二章 列表和元组,需要的朋友可以参考下

    优质Python教程 Python3.7从基础入门到精通进阶教程 第03章 列表、元组和字典的基本操作 共14页.ppt

    第2章 Python的基础语法.ppt 第3章 列表、元组和字典的基本操作.ppt 第4章 熟练操作字符串.ppt 第5章 程序的控制结构.ppt 第6章 函数.ppt 第7章 对象与类.ppt 第8章 程序调试和异常处理.ppt 第9章 模块与类库.ppt 第...

    python基础教程 第三版 中文 高清 pdf

    第2 章 列表和元组 2.1 序列概述 2.2 通用的序列操作 2.2.1 索引 2.2.2 切片 2.2.3 序列相加 2.2.4 乘法 2.2.5 成员资格 2.3 列表:Python的主力 2.3.1 函数 list 2.3.2 基本的列表操作 2.3.3 列表方法 ...

    Python基础教程(第2版.修订版)

    第2章 列表和元组 第3章 使用字符串 第4章 字典:当索引不好用时 第5章 条件、循环和其他语句 第6章 抽象 第7章 更加抽象 第8章 异常 第9章 魔法方法、属性和迭代器 第10章 充电时刻 第11章 文件和素材 第...

    Python基础教程(第2版 修订版)

     《图灵程序设计丛书:Python基础教程(第2版 修订版)》包括Python程序设计的方方面面,首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句。然后循序渐进...

    python基础教程第二版(高清书签中文)

    python 基础教程 第二版 高清 书签 中文: 本书包括Python程序设计的方方面面,首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句。然后循序渐进地介绍了...

    Python基础教程-第4章-Python-数据类型.pptx

    第4章 Python 数据类型 Python基础教程-第4章-Python-数据类型全文共70页,当前为第2页。 第4章 Python数据类型 学习目标 1.了解序列的含义,掌握序列的操作 2.了解字符串的概念,掌握字符串的操作,熟悉字符串的...

    Python基础教程(第2版•修订版)

    本书包括Python 程序设计的方方面面,首先从Python 的安装开始,随后介绍了Python 的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句。然后循序渐进地介绍了一些相对高级的主题,包括抽象、异常、...

    精品课件 Python从入门到精通 第2章 Python语言基础(共32页).ppt

    Python从入门到精通 第2章 Python语言基础.ppt Python从入门到精通 第3章 运算符与表达式.ppt Python从入门到精通 第4章 流程控制语句.ppt Python从入门到精通 第5章 列表与元组.ppt Python从入门到精通 第6章 字典...

    Python基础教程(第2版·修订版)pdf

    Python基础教程(第2版·修订版),pdf超清版,最低分普及Python了,同时附送:《深度学习中文版pdf-2017年3月.pdf》 ==== 本书包括Python程序设计的方方面面,首先从Python的安装开始,随后介绍了Python的基础知识...

    python基础教程至60课(基础)

    python基础教程至60课(基础) 【Python 第1课】安装 6 【Python 第2课】print 7 【Python 第3课】IDE 10 【Python 第4课】输入 12 【Python 第5课】变量 14 【Python 第6课】bool 16 【Python 第7课】if 19 【Python...

    Python3基础教程第4章.pptx

    第4章组合数据类型 本章主要内容: 集合 列表 元组 字典 迭代和列表解析 Python3基础教程第4章全文共118页,当前为第2页。 4.1 集合 集合(set)是Python 2.4引入的一种类型。 集合常量用大括号表示,例如,{1,2,3}...

    python基础教程2-4章.rar

    python教程(二)之列表与元组 python教程(三)之字符串操作 python教程(四)之字典(1.映射) python教程(四)之字典(2.基本操作) python教程(四)之字典(3.字典格式) python教程(四)之字典(4.字典方法...

    Python基础教程.rar

    学习python的书籍,里面包含的章节有第一章 基础知识,第二章 列表和元组 ,第三章 使用字符串 第四章到29章 最后有许多实例,可以进行编程练习

    赵璐python教程答案-《Python语言程序设计教程》赵璐著【摘要书评在线阅读】-苏宁 .pdf

    第1章 计算机基础及Python简介 1.1 计算机基础概述 1.2 Python语⾔的发展及现状 1.3 Python语⾔的特性与应⽤ 1.4 开发环境的安装及配置 本章⼩结 课后习题 第2章 编写简单的程序 2.1 ⽰例程序:求两个整数的和与...

    Python基础教程(第二版)

    《Python基础教程(第2版.修订版)》包括Python程序设计的方方面面,首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句。然后循序渐进地介绍了一些相对高级...

    Python基础教程(第2版 修订版).rar

    内容简介 《图灵程序设计丛书:Python基础教程(第2版 修订版)》包括Python程序设计的方方面面,首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字 符串、字典以及各种语句。...

Global site tag (gtag.js) - Google Analytics