python学习二--序列

来源:互联网 发布:facebook免费翻墙软件 编辑:程序博客网 时间:2024/06/03 17:06
序列

数据结构:通过一种方式组织在一起的数据元素的结合,这些元素可以是数字或者字符,甚至可以是其他数据结构。
python最基本的数据结构是序列。
序列中每个元素被分配一个序号--即元素的位置,也成为索引,第一个索引是0,第二个是1,以此类推。
也可以从最后一个元素计数,那么最后一个元素计为-1,第二个元素是-2,以此类推。

python包括6种内建序列,最常用的两种为:列表和元组。其他为:字符串、Unicode字符串、buffer对象、xrange对象。

列表和元组最主要的区别在于:列表可以修改,元组则不能修改。一般情况下在自己编写的程序中,几乎所有的情况下都可以用列表来
替代元组。
======================================
1、序列
>>> yujing = ['wolf',30]
>>> chennan = ['nannan',28]
>>> database = [yujing, chennan]   序列可以包含其他序列
>>> database
[['wolf', 30], ['nannan', 28]]

2、通用序列操作:
索引(indexing)、分片(slicing)、加(adding)、乘(multiplying)以及检查一个元素是否属于序列的成员。
除此之外,python可以计算序列长度,找出最大元素和最小元素的内建函数。

3、索引
序列中所有元素都有编号--从0开始。
>>> greeting = 'Hello'
>>> greeting[0]   索引0指向第一个元素
'H'
>>> greeting[1]
'e'
>>> greeting[-1]  使用负数索引时,也就是从最后1个元素开始计数。最后1个元素的位置编号是-1.
'o'

字符串的字符也可以直接索引,而不需要变量引用。
>>> 'wolf'[1]
'o'
>>> 'wolf'[0]
'w'

如果一个函数调用返回一个序列,那么可以直接对返回结果进行索引操作。
>>> fourth = raw_input('year:')[3]
year:2017
>>> fourth
'7'例如,假设只对用户输入年份的第4个数字感兴趣,那么,可以进行如下操作:
索引实例:
[root@node01 python]# vi rq.py       
months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
    ]

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)

month_name = months[month_number-1]
ordinal = day + endings[day_number - 1]

print month_name + ' ,' + ordinal + ' ,' + year
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
[root@node01 python]# python rq.py   
year:2017
month(1-12):12
day(1-31)16
December ,16th ,2017
================================================
1:first2:second3:third4:fourth5:fifth6:sixth7:seventh8:eighth9:ninth10:tenth11:eleventh12
:twelfth13:thirteenth14:fourteenth15:fifteenth16:sixteenth17:seventeenth18:eighteenth19
:ninteenth20:twentieth21:twentyfirst22:twenty-second23:twenty-third24:twenty-fourth25
:twenty-fifth26:twenty-sixth27;twenty-seventh28:twenty-eighth29:twenty-ninth30:thirtieth31
:thirty-first


endings = ['st','nd','rd']+ 17*['th']+['st','nd','rd']+ 7*['th']+['st']
================================================
4、分片
与使用索引来访问单个元素类似,可以使用分片操作来访问一琮范围内的元素。分片通过冒号相隔的两个索引来实现:
>>> tag = '<a href="http://www.python.org">Python web site</a>'
>>> tag[9:30]               #取第9个到第30个之间的字符
'http://www.python.org'
>>> tag[32:-4]              #取第32到第-4(倒着数第4个字符)
'Python web site'
实例:求10个数最后三个数:
>>> numbers = [0,1,2,3,4,5,6,7,8,9]
>>> numbers[7:-1]     # 从第7个数到 倒数第一个数
[7, 8]
>>> numbers[7:10]     #从第7个数到第10个数
[7, 8, 9]             这个也可以
>>> numbers[7:-2]
[7]
>>> numbers[7:-3]
[]
>>> numbers[6:-3]
[6]
>>> numbers[7:]        这个也可以
[7, 8, 9]
>>> numbers[:2]
[0, 1]
>>> numbers[:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[:]               这样可以取整个序列
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[3:6]
[3, 4, 5]
>>> numbers[3:6]
[3, 4, 5]                  
>>> numbers[0:1]
[0]
>>> numbers[-3:]
[7, 8, 9]             这个也可以


对http://fnng.cnblogs.com形式的URL进行分割
[root@node01 python]# vi yuming.py
#!/usr/bin/env python
url = raw_input('Please enter the URL:')
domain = url[11:-4]
print "Domain name:" + domain
[root@node01 python]# python yuming.py 
Please enter the URL:http://www.wolf.com
Domain name:wolf


更大的步长
普通的分片中,步长是1
>>> numbers = [0,1,2,3,4,5,6,7,8,9]
>>> numbers[0:10]             默认步长为1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[0:10:1]           默认步长为1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[0:10:2]   设置步长为2
[0, 2, 4, 6, 8]
>>> numbers[3:6:3]
[3]
>>> numbers[::4] 
[0, 4, 8]
>>> numbers[8:3:-1]  步长不能为0,但步长可以是负数,此时分片从右到左提取元素。
[8, 7, 6, 5, 4]
>>> numbers[10:0:-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> numbers[10:0:-2]
[9, 7, 5, 3, 1]
=====================================
5、序列相加
>>> [1,2,3] + [3,4,5]
[1, 2, 3, 3, 4, 5]
>>> '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
列表和字符串是无法连接接在一起的,尽管它他们都是序列。简单来说,两种相同类型的序列才能进行连接操作。
=====================================
6、乘法
>>> 'python ' * 5
'python python python python python '
>>> [32] * 10  
[32, 32, 32, 32, 32, 32, 32, 32, 32, 32]
如果想创建一个占用十个元素空间,却不包括任何有用的内容的列表,可以用None
none是python内建值。
>>> sequence = [None] * 10
>>> sequence
[None, None, None, None, None, None, None, None, None, None]
乘法实例:
[root@node01 python]# vi xl.py
#!/usr/bin/env python
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 + '|  ' + ' ' * text_width    + '  |'
print ' ' * left_margin + '|  ' +     sentence        + '  |'
print ' ' * left_margin + '|  ' + ' ' * text_width    + '  |'
print ' ' * left_margin + '+' + '-' * (box_width - 2)+ '+'


[root@node01 python]# python xl.py 
Sentence : wolf


                                   +--------+
                                   |        |
                                   |  wolf  |
                                   |        |
                                   +--------+
[root@node01 python]# python xl.py 
Sentence : laolang 123 


                               +----------------+
                               |                |
                               |  laolang 123   |
                               |                |
                               +----------------+
====================================
7、成员资格
>>> permissions = 'rw'
>>>  'w' in permissions
  File "<stdin>", line 1
    'w' in permissions
    ^
IndentationError: unexpected indent
>>>  'w' in permissions
  File "<stdin>", line 1
    'w' in permissions
    ^
IndentationError: unexpected indent
>>> 'w' in permissions
True
>>> 'x' in permissions
False
>>> users = ['wolf','laolang','nannan']
>>> raw_input('Enter your user name: ')in users
Enter your user name: wolf
True
>>> raw_input('Enter your user name: ')in users
Enter your user name: dd
False
>>> subjects ='$$$ Get rich now!!! $$$'
>>> '$$$' in subjects
True
>>> 'P' in 'Python'
True
实例:
#!/usr/bin/env python
database = [
  ['wolf', '110'],
  ['laolang', '111'],
  ['nannan', '112']
]
username = raw_input('User name: ')
pin = raw_input('PIN code: ')
if [username,pin] in database:print 'Access ok'


[root@node01 python]# python rw.py 
User name: laolang
PIN code: 111
Access ok
[root@node01 python]# python rw.py 
User name: nannan
PIN code: 111
[root@node01 python]# python rw.py 
User name: nannan
PIN code: 112
Access ok
==========================================
8、长度、最小值和最大值 
内建函数len、min 和max 非常有用。Len函数返回序列中所包含元素的数量。
Min函数和max函数则分别返回序列中最大和最小的元素。
>>> numbers = [100,34,678]
>>> len (numbers)
3
>>> max(numbers)
678
>>> max(numbers)
678
>>> max(2,3)
3
>>> min(9,3,2,5) 
2
==========================================
原创粉丝点击