python 序列
序列
序列是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 序列的更多相关文章
- [Python笔记][第二章Python序列-复杂的数据结构]
2016/1/27学习内容 第二章 Python序列-复杂的数据结构 堆 import heapq #添加元素进堆 heapq.heappush(heap,n) #小根堆堆顶 heapq.heappo ...
- [Python笔记][第二章Python序列-tuple,dict,set]
2016/1/27学习内容 第二章 Python序列-tuple tuple创建的tips a_tuple=('a',),要这样创建,而不是a_tuple=('a'),后者是一个创建了一个字符 tup ...
- [python笔记][第二章Python序列-list]
2016/1/27学习内容 第二章 Python序列-list list常用操作 list.append(x) list.extend(L) list.insert(index,x) list.rem ...
- python学习笔记:python序列
python序列包括字符串.列表和元组三部分,下面先总的说一下python序列共有的一些操作符和内建函数. 一.python序列 序列类型操作符 标准类型的操作符一般都能适用于所有的序列类型,这里说一 ...
- Python序列类型
Python序列类型 序列:字符.列表.元组 所有序列都支持迭代 序列表示索引为非负整数的有序对象集合 字符和元组属于不可变序列,列表可变 1)字符 字符串字面量:把文本放入单引号.双引号或三引号中: ...
- python 序列:字符串、列表、元组
python 序列:字符串.列表.元组 序列:包含一定顺序排列的对象的一个结构 内建函数:str() list() tuple() 可以使用str(obj)可以把对象obj转换成字符串 list( ...
- python序列元素引用容易出错的地方
python序列分列表和元组,不同之处在于元组的元素不能修改.元组使用小括号,列表使用方括号.元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可.举个简单的例子,a1是一个元组,a2是一个列表 ...
- Python——序列
#!/usr/bin/python #coding:utf8 ''' Python——序列 字符串的操作 ''' s = 'abcdefg' print s print s[2] print s[-1 ...
- python序列和其它类型的比较
序列对象可以与相同类型的其他对象比较.它们使用 字典顺序 进行比较:首先比较两个python序列的第一个元素,如果不同,那么这就决定了比较操作的结果.如果它们相同,就再比较每个序列的第二个元素,以此类 ...
- Python序列及其操作(常见)
python序列及函数入门认识: 0. 我们根据列表.元组和字符串的共同特点,把它们三统称为什么? 序列,因为他们有以下共同点: 1)都可以通过索引得到每一个元素 2)默认索引值总是从0开始(当 ...
随机推荐
- @EnableAsync annotation metadata was not injected
[问题描述] @EnableAsync annotation metadata was not injected spring配置初始化时候报错 nested exception is java.la ...
- 用mint ui去实现滚动选择日期并可以关闭拾取器
转发要备注出处哈,么么哒 注释的那些部分都是我在尝试的时候写得,留给自己看得,删除不影响效果哈,希望对你们有帮助,比较忙可能写得很粗糙,不好意思,有空再改了 实例一: <template&g ...
- 【次小生成树】bzoj1977 [BeiJing2010组队]次小生成树 Tree
Description 小 C 最近学了很多最小生成树的算法,Prim 算法.Kurskal 算法.消圈算法等等. 正当小 C 洋洋得意之时,小 P 又来泼小 C 冷水了.小 P 说,让小 C 求出一 ...
- select模型
在Windows中所有的socket函数都是阻塞类型的,也就是说只有网络中有特定的事件发生时才会返回,在没有发生事件时会一直等待,虽说我们将它们设置为非阻塞状态,但是在对于服务器段而言,肯定会一直等待 ...
- [转载]解决sudo: sorry, you must have a tty to run sudo
前几天遇到一个问题,在一个终端中调用另一个shell,始终是无法执行的,后来捕捉到报错信息为sudo: sorry, you must have a tty to run sudo,后来,在网上了解到 ...
- git>>>>1
参考博客:http://www.cnblogs.com/wupeiqi/p/7295372.html - 版本控制,各行各业都需要 - 版本控制工具 - svn - git - git,软件帮助使用者 ...
- hackerrank 训练军队
高阶传送魔法 在神奇的Kasukabe国家,人们努力拥有一个技能.一共有N个类型的技能,并且开始的时候拥有第 i 种技能的人有Ci个 . 这个国家有T个巫师,他们有能力将一个人的技能进行转换.每个巫师 ...
- Codeforces Round #404 (Div. 2)(A.水,暴力,B,排序,贪心)
A. Anton and Polyhedrons time limit per test:2 seconds memory limit per test:256 megabytes input:sta ...
- [bzoj1223] [HNOI2002]Kathy函数
首先由题解可得TAT,f(i)=i当且仅当i在二进制下为回文串. 那么问题就变成了1~n中有多少个二进制下的回文串. 把m转成2进制后就是正常的统计了= =. f[i]表示二进制下,有多少个i位的回文 ...
- android仿漫画源码、抽奖转盘、Google相册、动画源码等
Android精选源码 android实现仿今日头条的开源项目 波浪效果,实现流量的动态显示 美妆领域的app, 集成了摄像头取色, 朋友圈, 滤镜等 android仿漫画源码 android一个视差 ...