序列

序列是python中的一种数据结构,这种数据结构根据索引来获取序列中的对象

有6种内建序列类:list,tuple,string,unicode,buffer,xrange。 其中xrange比较特殊,是一个生成器

一般来说,具有序列结构的数据类型都可以使用:

index,len,max,min,in,+,*,切片

 >>> a='Iloveyou'
>>> len(a)
8
>>> max(a)
'y'
>>> min(a)
'I'
>>> type(a)
<type 'str'>
>>> id(a)
140666595185744
>>> id('Iloveyou')
140666595185744
>>> bool('o' in a)
True
>>> a+a
'IloveyouIloveyou'
>>> a*3
'IloveyouIloveyouIloveyou'
>>> a[1:4]
'lov'
>>> a.index('y')
5
>>> a[5]
'y'

切片操作

对具有序列结构的数据来说,切片操作的方法:consequence[start_index:end_index:step]

start_index: 表示是第一个元素对象,正索引位置默认为0;负索引位置默认为 -len(consequence)

end_index: 表示最后一个元素对象,正索引位置默认len(consequence)-1;负索引位置默认 -1

step: 表示取值的步长,默认为1,步长不能为0

[注意]对于序列结构数据来说,索引和步长都具有正负两个值,分别表示左右两个方向取值。索引的正方向从左往右取值,起始位置为0;负方向从右往左取值,起始位置为-1。因此任意一个序列结构数据的索引范围为 -len(consequence) 到 len(consequence)-1 范围内的连续整数。

 >>>
>>> a=[1,2,3,4,5,6,7]
>>> type(a)
<type 'list'>
>>> a[len(a)-1]
7
>>> a[-len(a)]
1
>>> a[-len(a)]
1
>>> a[len(a)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

其中a[len(a)-1]等同于a[-1],a[-len(a)]等同于a[0]

使用冒号对序列进行切片取值时,你所输入的无论是start_index或end_index,都不必局限于-len(a) 和len(a)-1 之间,因为只有当你输入的索引号处于这个区间时才真正有效,而当你输入的索引号超出这个范围,python会自动将start_index 或 end_index 设定为缺省值(即第一个对象和最后一个对象)

[注意]一定要记住,end_index其实是你第一个不想要获取的对象的索引,所以a[0:-1]是取不到a[-1]的,所以如果要使得切片片段包含end_index位置的对象,请缺省end_index,或者输入一个超出end_index范围的值。

利用步长对序列进行倒序取值

在切片运算中,步长为正,表示从左至右,按照索引值与起始位置索引之差可以被步长整除的规律取值;当步长为负,则表示从右至左,按照按照索引值与起始位置索引之差可以被步长整除的规律取值。

根据这个特性,我们可以很方便对某个序列进行倒序取值,这个方法比reverse方法更方便,且适用于没有reverse方法的字符串和元组。相对reverse而言,切片的方法不会改变列表的结构,所以这是在实际应用中比较有用的一个技巧。

 >>> a=[1,2,3,4,5,6,7,]
>>> a=[1,2,3,4,5,6,7]
>>> b=(1,2,3,4,5,6,7)
>>> type(b)
<type 'tuple'>
>>> type(a)
<type 'list'>
>>> c='Let me show you a little thing'
>>>
>>> a[::-1]
[7, 6, 5, 4, 3, 2, 1]
>>> b[::-1]
(7, 6, 5, 4, 3, 2, 1)
>>> c[::-1]
'gniht elttil a uoy wohs em teL'
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> b
(1, 2, 3, 4, 5, 6, 7)
>>> c
'Let me show you a little thing'
>>> a.reverse()
>>> a
[7, 6, 5, 4, 3, 2, 1]

更新列表

 #!/usr/bin/env python
# -*- coding:utf-8 -*- list = ['physics','chemistry',1997,2000]
print "Value available at index 2 :"
print list[2]
list[2]=2001
print "New value available at index 2 :"
print list[2]
# 结果
[root@localhost 20170120]# python xulie.py
Value available at index 2 :
1997
New value available at index 2 :
2001

删除列表元素

#!/usr/bin/env python
# -*- coding:utf-8 -*-
list = ['physics','chemistry',1997,2000] print list
del list[2]
print "After deleting value at index 2 : "
print list
#结果
[root@localhost 20170120]# python xulie.py
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

创建list有很多方法:

1.使用一对方括号创建一个空的list:[]
2.使用一对方括号,用','隔开里面的元素:[a, b, c], [a]
3.Using a list comprehension:[x for x in iterable]
4.Using the type constructor:list() or list(iterable)

'''

def create_empty_list():
'''Using a pair of square brackets to denote the empty list: [].'''
return [] def create_common_list():
'''Using square brackets, separating items with commas: [a], [a, b, c].'''
return ['a', 'b', 'c', 1, 3, 5] def create_common_list2():
'''Using a list comprehension: [x for x in iterable].'''
return [x for x in range(1, 10)] def str_to_list(s):
'''Using a string to convert list'''
if s != None:
return list(s)
else:
return [] def main():
test_listA = create_empty_list()
print(test_listA)
print('#' * 50)
test_listB = create_common_list()
print(test_listB)
print('#' * 50)
test_listC = create_common_list2()
print(test_listC)
print('#' * 50)
test_str = 'i want to talk about this problem!'
test_listD = str_to_list(test_str)
print(test_listD) if __name__ == '__main__':
main()

  

2、tuple 转 list

#!/usr/bin/env python
# -*- coding:utf-8 -*- aTuple=(12,3,'a','yy')
aList=list(aTuple)
print "aTyple type is: ",type(aTuple)
print "aList type is: ",type(aList)
print "aList's value is: ",aList

运行结果

[root@localhost 20170120]# python tuple2list.py
aTyple type is: <type 'tuple'>
aList type is: <type 'list'>
aList's value is: [12, 3, 'a', 'yy']

3、tuple与list相似,但是tuple不能修改,tuple使用小括号,列表用方括号

tuple创建,只需在括号中添加元素,并使用逗号隔开即可

tuple创建只包含一个元素时,需在元素后面添加逗号

tup1=(50,)

 >>> tup1 = ("all")
>>> print tup1
all
输出字符串 all,这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号。
所以,如果元组只有1个元素,就必须加一个逗号,防止被当作括号运算:
>>> tup1 = ("all",)
>>> print tup1
('all',)
>>>
[root@localhost 20170120]# cat tuple.py
#!/usr/bin/env python
# -*- coding:utf-8 -*- tup1=('physics','chemistry',1997,2000);
tup2=(1,2,3,4,5,6,7,8,9); print "tup1[0]:",tup1[0];
print "tup2[1:5]:",tup2[1:5];
[root@localhost 20170120]# python tuple.py
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)

修改元组

元组中的元素不能修改,但可以对元组进行连接组合

#代码
#!/usr/bin/env python
# -*- coding:utf-8 -*- tup1=(12,34.56)
tup2=('abc','xyz') tup3=tup1+tup2
print tup3 #运行结果
[root@localhost 20170120]# python tuple.py
(12, 34.560000000000002, 'abc', 'xyz')

删除元组

#!/usr/bin/env python
# -*- coding:utf-8 -*- tup1=('physics','chemistry',1997,2000);
print tup1
del tup1
print "After deleting tup1:"
print tup1 #执行结果
[root@localhost 20170120]# python tuple.py
('physics', 'chemistry', 1997, 2000)
After deleting tup1:
Traceback (most recent call last):
File "tuple.py", line 8, in <module>
print tup1
NameError: name 'tup1' is not defined
#!/usr/bin/env python
# -*- coding:utf-8 -*- list01=['runoob',786,2.23,'john',70.2]
list02=[123,'john'] print list01
print list02 print "列表截取"
print list01[0]
print list01[-1]
print list01[0:3] print "列表重复"
print list01 * 2 print "列表组合"
print list01 + list02 print "获取列表长度"
print len(list01) print "删除列表元素"
del list02[0]
print list02 print "元素是否存在于列表中"
print 'john' in list02 print "迭代"
for i in list01:
print i print "比较两个列表的元素"
print cmp(list01,list02) print "列表最大/最小值"
print max([0,1,2,3,4])
print min([0,1]) print "将元组转换为列表"
aTuple = (1,2,3,4)
list03=list(aTuple)
print list03 print "在列表末尾添加新的元素"
list03.append(5)
print list03 print "在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)"
list03.extend(list01)
print list03 print "统计某个元素在列表中出现的次数"
print list03.count(1) print "从列表中找出某个值第一个匹配项的索引位置"
print list03.index('john') print "将对象插入列表"
list03.insert(0,'hello')
print list03 print "移除列表中的一个元素(默认最后一个元素),并且返回该元素的值"
print list03.pop(0)
print list03 print "移除列表中某个值的第一个匹配项"
list03.remove(1)
print list03 print "反向列表中元素"
list03.reverse()
print list03 print "对原列表进行排序"
list03.sort()
print list03
#结果
[root@localhost 20170120]# python xulie.py
['runoob', 786, 2.23, 'john', 70.200000000000003]
[123, 'john']
列表截取
runoob
70.2
['runoob', 786, 2.23]
列表重复
['runoob', 786, 2.23, 'john', 70.200000000000003, 'runoob', 786, 2.23, 'john', 70.200000000000003]
列表组合
['runoob', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
获取列表长度
5
删除列表元素
['john']
元素是否存在于列表中
True
迭代
runoob
786
2.23
john
70.2
比较两个列表的元素
1
列表最大/最小值
4
0
将元组转换为列表
[1, 2, 3, 4]
在列表末尾添加新的元素
[1, 2, 3, 4, 5]
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
[1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]
统计某个元素在列表中出现的次数
1
从列表中找出某个值第一个匹配项的索引位置
8
将对象插入列表
['hello', 1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
hello
[1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]
移除列表中某个值的第一个匹配项
[2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.200000000000003]
反向列表中元素
[70.200000000000003, 'john', 2.23, 786, 'runoob', 5, 4, 3, 2]
对原列表进行排序
[2, 2.23, 3, 4, 5, 70.200000000000003, 786, 'john', 'runoob']

参考:

1、http://www.cnblogs.com/ifantastic/archive/2013/04/15/3021845.html

python 序列的更多相关文章

  1. [Python笔记][第二章Python序列-复杂的数据结构]

    2016/1/27学习内容 第二章 Python序列-复杂的数据结构 堆 import heapq #添加元素进堆 heapq.heappush(heap,n) #小根堆堆顶 heapq.heappo ...

  2. [Python笔记][第二章Python序列-tuple,dict,set]

    2016/1/27学习内容 第二章 Python序列-tuple tuple创建的tips a_tuple=('a',),要这样创建,而不是a_tuple=('a'),后者是一个创建了一个字符 tup ...

  3. [python笔记][第二章Python序列-list]

    2016/1/27学习内容 第二章 Python序列-list list常用操作 list.append(x) list.extend(L) list.insert(index,x) list.rem ...

  4. python学习笔记:python序列

    python序列包括字符串.列表和元组三部分,下面先总的说一下python序列共有的一些操作符和内建函数. 一.python序列 序列类型操作符 标准类型的操作符一般都能适用于所有的序列类型,这里说一 ...

  5. Python序列类型

    Python序列类型 序列:字符.列表.元组 所有序列都支持迭代 序列表示索引为非负整数的有序对象集合 字符和元组属于不可变序列,列表可变 1)字符 字符串字面量:把文本放入单引号.双引号或三引号中: ...

  6. python 序列:字符串、列表、元组

    python 序列:字符串.列表.元组   序列:包含一定顺序排列的对象的一个结构 内建函数:str() list() tuple() 可以使用str(obj)可以把对象obj转换成字符串 list( ...

  7. python序列元素引用容易出错的地方

    python序列分列表和元组,不同之处在于元组的元素不能修改.元组使用小括号,列表使用方括号.元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可.举个简单的例子,a1是一个元组,a2是一个列表 ...

  8. Python——序列

    #!/usr/bin/python #coding:utf8 ''' Python——序列 字符串的操作 ''' s = 'abcdefg' print s print s[2] print s[-1 ...

  9. python序列和其它类型的比较

    序列对象可以与相同类型的其他对象比较.它们使用 字典顺序 进行比较:首先比较两个python序列的第一个元素,如果不同,那么这就决定了比较操作的结果.如果它们相同,就再比较每个序列的第二个元素,以此类 ...

  10. Python序列及其操作(常见)

    python序列及函数入门认识: 0. 我们根据列表.元组和字符串的共同特点,把它们三统称为什么?    序列,因为他们有以下共同点: 1)都可以通过索引得到每一个元素 2)默认索引值总是从0开始(当 ...

随机推荐

  1. PyQt4中的Treeview

    import sys from PyQt4 import QtCore, QtGui from qyolk import Ui_QYolk from yolk import yolklib class ...

  2. Effective Java 第三版——19. 如果使用继承则设计,并文档说明,否则不该使用

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  3. oracle如何导出和导入数据库表

    oracle如何导出和导入数据库表 oracle如何将项目中的表导出后在导入自己的数据库中,这是一个完整的操作,对于数据库备份或在本地查看数据验证数据进场用到,一般情况下我都用dos黑窗口进行操作,简 ...

  4. Django-数据库访问优化

    数据库访问优化 使用标准数据库优化技巧 索引.我们可以使用Field.db_index或者Meta.index_together在Django中添加索引,优先向经常使用filter(),exclude ...

  5. keynote 代码高亮

    brew install highlight (同时会安装 Lua 和 Boost) highlight -K 18 -s Vampire -u 'utf-8' -O rtf test.html | ...

  6. cyclictest 简介

    1. cyclictest 简介以及安装 1.1 cyclictest 简介 cyclictest 是什么? 看名字应该就能大致猜出来它是一种 test 程序,Cyclictest的维基主页这么介绍它 ...

  7. 解决前端开发sublime text 3编辑器无法安装插件的问题

    今天在笔记本电脑上安装了个sublime,但是却出现无法装插件的问题.于是稍微在网上查了些资料,并试验了一番,写了如下文章. 安装插件的步骤: 弹出 选中install package 如果出现如下问 ...

  8. 原来你是这样的JAVA[03]-继承、多态、抽象类

    一.继承 Java中的继承使用关键字extends ,跟C#的语法略有差别. 1.子类构造器 java会自动在子类的构造器中插入对父类构造器的调用,也就是说在子类可以访问父类之前已经完成了父类的初始化 ...

  9. 手机termux上安装msfconsole

    大家可能因为手机没有root而不能通过deploy安装kali 我们使用termux来安装渗透工具 1.下载并安装Termux,更新软件源并升级软件包 apt update apt upgrade a ...

  10. BC#65 T5 ZYB's Prime

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=5594 完全不会啊TAT.. 其实官方题解已经说的很清楚了.. #include <cstdio> ...