码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础教程之第2章 列表和元组

时间:2015-12-23 21:18:37      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:

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章 列表和元组

标签:

原文地址:http://www.cnblogs.com/hrhguanli/p/5071054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!