Python数据类型——序列(字符串,列表,元组)

上一篇 / 下一篇  2017-06-14 14:19:27 / 个人分类:python

http://blog.csdn.net/alexbnlee/article/details/6966525

Python的数据访问模型:直接存取 ,序列 ,映射

对非容器类都可以直接存取,所有的数值类型归为此类。

序列类型是指容器内的元素从0开始的索引顺序访问,一次可以访问一个或者多个元素。 字符串列表元组归到次类

映射类型和序列类型不同之处,它使用的索引和顺序的数字偏移量不同,它的元素无序存放,通过唯一的key来访问。 字典就是这种类型。

 

 

下面要说的字符串(strings),列表(lists),元组(tuples),我们可以统称为序列。

序列有着相同的访问模式:它的每一个元素都可以通过指定一个偏移量的方式得到,而要想一次得到多个元素,我们可以使用切片,下表偏移量从0开始,总元素数减1结束。

 

下面举几个例子,先看看什么事字符串,列表,元组。

 

字符串:
>>> a = 'HelloPython!'

>>> a

'Hello python!'

>>> b = "This is'Python'"

>>> b

"This is 'Python'"

>>> c = 'This is"Python"'

>>> c

'This is "Python"'

>>>

 

列表:

>>> a = [1, 2, 3, 4,5]

>>> a

[1, 2, 3, 4, 5]

>>> b = [1, 'a', 2.5,2+3j, "this is python list"]

>>> b

[1, 'a', 2.5, (2+3j), 'this is pythonlist']

>>>

 

元组:

>>> a = (1, 3, 5,7)

>>> a

(1, 3, 5, 7)

>>> a = ('a',2)

>>> a

('a', 2)

>>>

 

 

下面看一下序列通用的几个操作符:

1 连接操作符(+) 这个操作符允许我们把一个序列和另一个相同的序列做链接。

Sequence1+sequence2 结果是包含两个原序列内容的新序列。

 

>>> a = 'this is '

>>> b = 'Python'

>>> a+b

'this is Python'

>>>

 

2 重复操作符(*)

当你需要一个序列的多份拷贝时,重复操作符非常有用。

Sequence * copies_int

Copies_int必须为整型。

 

>>> a

'this is Python'

>>> a*3

'this is Pythonthis is Pythonthis isPython'

>>>

 

>>> b = [1, 2, 3]

>>> b*3

[1, 2, 3, 1, 2, 3, 1, 2, 3]

>>>

 

 

3 切片操作符 [ ] [:] [: : ]

切片操作符应该是由最简单的取单个元素的操作扩展而来的。通常sequence[n]代表取出序列中第n+1个元素(因为元素下标从0开始)

>>> a = 'Python'

>>> a[2]

't'

>>> b = [1, 2, 3,4]

>>> b[2]

3

>>> c = (1, 2, 3)

>>> c[2]

3

>>>

当中括号里面有个:的时候,代表冒号两边的数字规定了两个位置,我们把处于这个位置之中的所有元素取了出来。如果冒号两边什么都没有,代表取出所有元素,如果两边有数,例如sequence[m:n]就是代表取出从下标为m的元素到下标为n-1的所有元素。如果中括号里两个冒号,那么两个冒号后面的数代表步长,就是隔几个元素取一次。下面一字符串为例详细说明。(其他的序列操作类似)

>>> a = 'Python'

>>> a[1]

'y'

>>> a[:]

'Python'

>>> a[1:4]

'yth'

>>> a ='10001000100010001'

>>> a[0:17:4]

'11111'

>>>

另外切片支持负数操作。比如

>>> a = 'Python'

>>> a[-1]

'n'

>>> a[-2]

'o'

>>> a[-6]

'P'

>>>

由此我们就可以很随意的取元素了。但是注意一点,平时我们不加步长,是因为我们默认是顺序取,并且步长为1,假如我们要倒着取,步长必须为负数才行,否则取的不正确。

>>> a = 'Python'

>>> a[-2:-4]

''                  这是错误的

>>> a[-4:-2]

'th'

>>> a[-2:-4:-1]

'oh'

>>> a[::-1]

'nohtyP'

>>>

4 成员操作符( in , not in )

 

>>> a = 'Python'

>>> 'p' in a

False

>>> 'y' in a

True

>>> b = [1, 2, 3,4]

>>> 1 in b

True

>>> 5 in b

False

>>>

 

序列的一些常用的公用函数:

1 len() 获得序列的长度

 

>>> a = 'ddddddd'

>>> b = [1, 3, 4,4]

>>> c = (1,3,4,4)

>>> len(a)

7

>>> len(b)

4

>>> len(c)

4

>>>

得出一点结论,Python字符串和C字符串不同的地方,Python字符串不会以空字符结尾

 

2 max() and min() 获得序列中最大和最小元素

 

>>> a = 'abcdefg'

>>> b = [1, 3, 5,8]

>>> c = (2, 5, 1,0)

>>> d =['a',3,45,9]

>>> max(a)

'g'

>>> max(d)

'a'

>>> min(b)

1

>>> min(c)

0

>>>

 

 

下面接着看看标准内建函数:

1 type(object) 接受一个对象作为参数,并返回它的类型。

 

>>type(2)

>><type‘int’>

>>type(‘a’)

>><type‘str’>

 

2 cmp()  比较大小

 

>>> a = 4

>>> b = 8

>>> cmp(a,b)

-1

>>> cmp(b,a)

1

>>> a = 3

>>> b = 3

>>> cmp(a,b)

0

>>> a = 'lmn'

>>> b = 'abc'

>>> cmp(a,b)

1

>>>

 

3 str()  和repr()

 

>>> str(4.53-2j)

'(4.53-2j)'

>>> str(1)

'1'

>>> str([1, 3, 4,5])

'[1, 3, 4, 5]'

>>> repr([1, 3, 4,5])

'[1, 3, 4, 5]'

>>> '[1, 3, 4, 5]'

'[1, 3, 4, 5]'

>>>

-----------------------------------------------------------------------------------------------------------------------------

下面就看一看字符串,列表,元组各自常有的操作符和内建函数:

字符串

首先我觉得最重要的就是字符串的格式化输出了”%”(Formatting)

 

>>> format ="Hello,%s,%s enough for ya?"

>>> values =('world','Hot')

>>> print format %values

Hello,world,Hot enough for ya?

>>> 

 

%代表了要插入的位置,s代表了要插入的数据类型是str,因为这里我们要插入两个地方,所以我们用到了values这个元组。注意,格式化输出要插入多个数据的时候,只有元组和字典具有这个资格,不能使用列表,列表只能代表一个数据。

>>> values =['world','Hot']

>>> print format %values

Hello,['world', 'Hot'] enough for ya?

>>> 

 

>>> print 'you areNo.%s' % 1

you are No.1 

 

如果给的数据不是str类型的,%s会自动用str()把它转换为str类型

如果要格式化输出一个控制精度的浮点数,可以如下:

>>> PI =3.1415926

>>> print "PI is%.3f" % PI

PI is 3.142

>>> 

 

但是从上面可以看到,使用格式化操作符还是不方便的,因为经常要注意格式转换的问题,%s格式系统会自动为我们转换那些输入不是str类型的数据,但是别的格式化输出符,还是需要我们自己去转化,如果要输出的格式有好多种,用起来还是比较复杂的。

 

Template strings字符串模板            

 

字符串模板使我们不用去管输出传递的细节,而是像现在shell风格的脚本里面使用符号“$”

 

>>> from stringimport Template

>>> s =Template("There are ${howmany} ${lang} Quotation Symbols")

>>> prints.substitute(lang='Python',howmany=3)

There are 3 Python Quotation Symbols

>>>s.substitute(lang='Python',howmany=3)

'There are 3 Python Quotation Symbols'

>>> prints.substitute(lang='Python')

 

Traceback (most recent call last):

  File"<pyshell#50>", line 1, in<module>

    prints.substitute(lang='Python')

  File "C:\Python26\lib\string.py", line 170,in substitute

    returnself.pattern.sub(convert, self.template)

  File "C:\Python26\lib\string.py", line 160,in convert

    val =mapping[named]

KeyError: 'howmany'

>>> prints.safe_substitute(lang='Python',howmany=3)

There are 3 Python Quotation Symbols

>>> prints.safe_substitute(howmany=3)

There are 3 ${lang} Quotation Symbols

>>> 

 

Template对象有两个方法,substitute()  和safe_substitute()前者更为严谨,在key缺少的情况下会报错KeyError,而后者在缺少Key时,直接安缺少的情况把字符串输出显示出来。

在这里如果要输出$符号,我们可以用$$

 

String Methods 字符串函数

 

1 find() 查找某个字符在字符串中是否存在,并返回结果。找到返回位置,没有则返回-1

 

>>> title = "MontyPython's Flying Circus"

>>>title.find("Monty")

0

>>>title.find('Python')

6

>>>title.find('Flying')

15

>>>title.find('Zirquss')

-1

>>> 

 

Find也可以带参数,来限制查找的范围,比如:find(’a’,1,10)

 就是查找字符’a’,查找范围是从标号为1的元素开始到标号为9的元素截止(和切片类似)。

 

2 join()函数

 

>>> seq = ['1','2', '3', '4', '5']

>>> sep = '+'

>>>sep.join(seq)

'1+2+3+4+5'

>>> seq

['1', '2', '3', '4', '5']

>>>'+'.join(seq)

'1+2+3+4+5'

>>>'%'.join(seq)

'1%2%3%4%5'

>>>'#$%'.join(seq)

'1#$%2#$%3#$%4#$%5'

>>> dirs = '','usr','bin','env'

>>>'/'.join(dirs)

' /usr/bin/env'

>>> print'C:'+'\\'.join(dirs)

C: \usr\bin\env

>>> 

 

      lower()

>>> "TrindhermHammer Dance".lower()

'trindherm hammer dance'

>>> 

 

      replace()  替换

 

 >>>"This is a test".replace('is','AAA')

'ThAAA AAA a test'

>>> 

字符串的函数很多,而且参数也有变化,功能也多,这里就不一一列举了。

 

 

 

列表

列表也是序列式的数据类型,可以通过下标或者切片操作来访问一个或者多个元素。列表和字符串不同的地方在,字符串只能由字符组成,而且不是可变的(不能单独改变它的某个值),而列表则是保存任何数目的Python对象的灵活的容器。

 

对列表的一些操作:
1 访问列表中的元素

 

>>>alist = [1, 2,3, 4]

>>>alist[1]

2

>>> 

另外列表和其他序列一样,也可以进行切片操作

 

2更新列表的元素,看下面的例子:

 

>>> str1 = "stringcan not be changed"

>>> str1[0]

's'

>>> str1[0]='S'

 

Traceback (most recent call last):

  File"<pyshell#2>", line 1, in<module>

   str1[0]='S'

TypeError: 'str' object does not support item assignment

>>> tuples1 = (1,2, 3, 4)

>>> tuples1[0]

1

>>> tuples1[0] =2

 

Traceback (most recent call last):

  File"<pyshell#5>", line 1, in<module>

   tuples1[0] = 2

TypeError: 'tuple' object does not support item assignment

>>> list1 = [1,'a', 3, 5]

>>> list1[1]

'a'

>>> list1[1] ='b'

>>> list1

[1, 'b', 3, 5]

>>> 

可以看到,同样作为序列的字符串和元组,值是不可改变的,我们可以改变的只能是给他重新赋值,然后以前的值会被销毁。但是列表却不同,列表可以对其里面的任意元素做任意操作,改变,添加,删除等等。

 

3  del 删除操作:

 

>>> list1

[1, 'b', 3, 5]

>>> dellist1[0]

>>> list1

['b', 3, 5]

>>> del list1

>>> list1

 

Traceback (most recent call last):

  File"<pyshell#17>", line 1, in<module>

    list1

NameError: name 'list1' is not defined

>>> 

Del既可以删除一个元素,也可以删除整个列表。

 

      append 在列表结尾添加新元素:

 

>>> lst = [1, 2,3]

>>>lst.append(4)

>>> lst

[1, 2, 3, 4]

>>> 

 

6 count 返回该元素的个数

 

>>> lst = [1, 2, 2,3, 3, 3]

>>>lst.count(1)

1

>>>lst.count(2)

2

>>>lst.count(3)

3

>>> 

 

      extend 允许你一次把列表扩展多个元素

 

>>> a = [1, 2,3]

>>> b = [4, 5,6]

>>> a.extend(b)

>>> a

[1, 2, 3, 4, 5, 6]

>>> a = [1, 2,3]

>>> b = [4, 5,6]

>>> a+b

[1, 2, 3, 4, 5, 6]

>>> a

[1, 2, 3]

>>> 

可以看出和”+”操作还是不同的

 

      index 返回元素的位置

>>> ind =['Python', 'is', 'powerful']

>>>ind.index('is')

1

>>> 

      insert 插入一个元素

>>> numbers = [1,2, 3, 5, 6, 7]

>>>numbers.insert(3,'four')

>>> numbers

[1, 2, 3, 'four', 5, 6, 7]

>>> 

Insert 第一个参数表示要插入的位置,第二是要插入的内容。

 

      pop 和 remove

>>> numbers

[1, 2, 3, 'four', 5, 6, 7]

>>>numbers.remove('four')

>>> numbers

[1, 2, 3, 5, 6, 7]

>>> 

Remove类似于del

>>> numbers

[1, 2, 3, 5, 6, 7]

>>>numbers.pop()

7

>>> numbers

[1, 2, 3, 5, 6]

>>>numbers.pop(0)

1

>>> numbers

[2, 3, 5, 6]

>>> 

Pop不带参数,是把列表最后一个元素删除了,当然可以指定位置。

10 reverse   翻转

>>> numbers

[2, 3, 5, 6]

>>>numbers.reverse()

>>> numbers

[6, 5, 3, 2]

>>> 

 

10    排序sort()

>>> x = [4, 6, 1,7, 2, 5, 3]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7]

>>> x =['abcdefg','ab','abcd','a','abc']

>>>x.sort(key=len)

>>> x

['a', 'ab', 'abc', 'abcd', 'abcdefg']

>>> x = [1, 2, 3,4, 5, 6]

>>>x.sort(reverse=True)

>>> x

[6, 5, 4, 3, 2, 1]

 

使用命令dir(list)可以列出列表的全部方法和属性,这里不一一举例了。

>>> dir(list)

['__add__', '__class__', '__contains__', '__delattr__','__delitem__', '__delslice__', '__doc__', '__eq__', '__format__','__ge__', '__getattribute__', '__getitem__', '__getslice__','__gt__', '__hash__', '__iadd__', '__imul__', '__init__','__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__','__new__', '__reduce__', '__reduce_ex__', '__repr__','__reversed__', '__rmul__', '__setattr__', '__setitem__','__setslice__', '__sizeof__', '__str__', '__subclasshook__','append', 'count', 'extend', 'index', 'insert', 'pop', 'remove','reverse', 'sort']

>>> 

 

 

元组

 

元组是跟列表非常相近的另外一种容器类型,两者重要不同点是:元组和字符串一样,是一种不可变类型。

 

关于元组的创建,访问,切片等一些序列公有的操作这里就不说了。

 

元组是不可改变的,也就说不能对元组的某一个元素进行改变,但是我们可以对整个元素进行重新赋值,同样能达到对元组进行改变的目的,比如:

 

>>> aTuple = (1,'a', 2, 'b', 'c')

>>> aTuple =aTuple[0],aTuple[2]

>>> aTuple

(1, 2)

>>> 

 

下面是元组的一些操作:

>>> dir(tuple)

['__add__', '__class__', '__contains__', '__delattr__','__doc__', '__eq__', '__format__', '__ge__', '__getattribute__','__getitem__', '__getnewargs__', '__getslice__', '__gt__','__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__','__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__','__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__','__subclasshook__', 'count', 'index']

来源:http://blog.sina.com.cn/s/blog_4b5039210100e9yd.html

来源:http://blog.sina.com.cn/s/blog_4b5039210100e9yg.html


TAG: 字符串

 

评分:0

我来说两句

日历

« 2024-03-20  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 43996
  • 日志数: 54
  • 建立时间: 2017-04-28
  • 更新时间: 2018-01-25

RSS订阅

Open Toolbar