Python基础(3)--列表和元组

简介:

Python包含6种内建序列:列表、元组、字符串、Unicode字符串、buffer对象、xrange对象

本篇主要讨论最常用的两种类型:列表、元组

本文地址:http://www.cnblogs.com/archimedes/p/python-list-tuple.html,转载请注明源地址。

列表和元组的主要区别在于,列表可以修改,元组则不能。一般情况下,在几乎所有的情况下列表都可以代替元组

例如:使用序列可以表示数据库中一个人的信息(姓名,年龄)

>>> edward=['Edward Gumby',42]

序列还可以包含其他序列

>>> edward=['Edward Gumby',42]
>>> john=['John Smith',50]
>>> database=[edward,john]
>>> database
[['Edward Gumby', 42], ['John Smith', 50]]

通用序列操作

所有的序列操作都可以进行某些特定的操作。这些操作包括:索引、分片、加、乘以及检查某个元素是否属于序列的成员

索引

序列中的所有元素都是有编号的--从0开始递增。这些元素可以通过编号分别访问,如下:

>>> greeting='hello'
>>> greeting[0]
'h'
>>> greeting[-1]
'o'
>>> 'hello'[1]
'e'

如果一个函数调用返回一个序列,那么可以直接对返回结果进行索引操作,例如:

>>> fourth=raw_input('Year:')[3]
Year:2005
>>> fourth
'5'
#根据给定的年月日以数字形式打印出日期
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

运行结果:

>>> 
Year: 1974
Month(1-12): 8
Day(1-31): 16
August 16th, 1974

分片

使用分片操作来访问一定范围内的元素,分片通过冒号相隔的两个索引来实现:

>>> tag='<a herf="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]
[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、更大的步长

分片还有第三个参数--步长,通常都是隐式设置的,在一般情况下,步长是1,不能为0,但是可以为负数,即从右往左提取元素

>>> numbers=[1,2,3,4,5,6,7,8,9,10]
>>> 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[10: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[:5:-2]
[10, 8]

序列相加

通过使用加号可以进行序列的连接操作:

>>> [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 "<pyshell#107>", line 1, in <module>
    [1,2,3]+'world!'
TypeError: can only concatenate list (not "str") to list

乘法

用数字x乘以一个序列会生成新的序列,而在新的序列中,原来的序列将被重复x次

>>> 'python'*5
'pythonpythonpythonpythonpython'
>>> [42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]

成员资格

为了检查一个值是否在序列中,可以使用in运算符,该运算符返回布尔值

>>> permissions='rw'
>>> 'w'in permissions
True
>>> 'x'in permissions
False
Enter your name: mlh
True
>>> subject='$$$ Get rich now!!! $$$'
>>> '$$$'in subject
True

长度、最小值和最大值

内建函数len、min、max,len函数返回序列中所包含元素的数量,min和max函数分别返回序列中最大和最小的元素

>>> numbers=[100,34,678]
>>> len(numbers)
3
>>> max(numbers)
678
>>> min(numbers)
34
>>> max(2,3)
3
>>> min(9,3,2,5)
2

list函数

list函数可以根据字符串创建列表

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

基本列表操作:

1、改变列表:元素赋值

使用索引标记来为某个特定的、位置明确的元素赋值:

>>> x=[1,1,1]
>>> x[1]=2
>>> x
[1, 2, 1]

2、删除元素

使用del语句来实现:

>>> names=['Alice','Beth','Ceil','Dee-Dee','Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']

注意:Cecil是彻底删除,列表长度也从5变为4

3、分片赋值

>>> names
['p', 'e', 'r', 'l']
>>> names[2:]
['r', 'l']
>>> name=list('perl')
>>> name
['p', 'e', 'r', 'l']
>>> name[2:]=list('ar')
>>> name
['p', 'e', 'a', 'r']
>>> name[1:]=list('ython')
>>> name
['p', 'y', 't', 'h', 'o', 'n']

>>> numbers=[1,5]
>>> numbers[1:1]=[2,3,4]
>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[1:4]=[]
>>> numbers
[1, 5]

列表方法:

方法是一个与某些对象有紧密联系的函数,对象可能是列表、数字,也可能是字符串或者其他类型的对象,方法的调用方式:对象.方法(参数)

1、append

append方法用于在列表末尾追加新的对象:

>>> lst=[1,2,3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

2、cout

count方法用于统计某个元素在列表中出现的次数:

>>> ['to','be','or','not','to','be'].count('to')
2
>>> x=[[1,2],1,1,[2,1,[1,2]]]
>>> x.count(1)
2
>>> x.count([1,2])
1

3、extend

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]

4、index

index方法用于从列表中找出某一个匹配项的索引位置:

>>> knights=['we','are','the','knigths','who','say','ni']
>>> knights.index('who')
4
>>> knights=['we','are','the','knigths','who','say','ni']
>>> knights.index('herring')

Traceback (most recent call last):
  File "<pyshell#184>", line 1, in <module>
    knights.index('herring')
ValueError: 'herring' is not in list

没有成功找到会引发异常

 5、insert

insert方法用于将对象插入到列表中:

>>> numbers=[1,2,3,5,6,7]
>>> numbers.insert(3,'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]
>>> #extend方法一样,insert方法的操作也可以用分片赋值来实现
>>> numbers=[1,2,3,5,6,7]
>>> numbers[3:3]=['four']
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]

6、pop

pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值:

>>> x=[1,2,3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]

注意:pop方法是唯一一个既能修改列表又返回元素值(除了None)的列表方法

7、remove

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 "<pyshell#19>", line 1, in <module>
    x.remove('bee')
ValueError: list.remove(x): x not in list

8、reverse

reverse方法将列表中的元素反向存放,该方法也改变了列表但不返回值

>>> x=[1,2,3]
>>> x.reverse()
>>> x
[3, 2, 1]

9、sort

sort方法用于在原位置对列表进行排序,改变原来的列表,从而让其中的元素按照一定的

>>> x=[4,6,2,1,7,9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]

 


 元组

元组与列表一样,也是一种序列,唯一不同的是元组不可以修改:

  • 任意对象的有序集合
  • 通过偏移存储
  • 属于不可变序列类型
  • 固定长度、异构、任意嵌套
  • 对象引用数组

使用逗号分隔了一些值,就自动创建了一个元组:

>>> 1,2,3
(1, 2, 3)
>>> ()
()
>>> 42
42
>>> 42,
(42,)
>>> (42,)
(42,)

元组也是(大部分时候是)通过圆括号括起来的,空元组可以用没有包含内容的两个圆括号来表示:

tuple函数

tuple函数的功能和list函数基本上是一样的:以一个序列作为参数并把它转换为元组。

>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)

列表与元组的相互转化:

>>> T=('cc','aa','dd','bb')
>>> tmp=list(T)
>>> tmp
['cc', 'aa', 'dd', 'bb']
>>> T=tuple(tmp)
>>> T
('cc', 'aa', 'dd', 'bb')
目录
相关文章
|
1月前
|
存储 算法 数据挖掘
python列表简介(二)
python列表简介(二)
31 2
|
7天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
44 0
|
7天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
8天前
|
存储 索引 Python
python学习7-元组
python学习7-元组
|
8天前
|
存储 索引 Python
python学习5-列表的创建、增删改查、排序
python学习5-列表的创建、增删改查、排序
|
11天前
|
存储 安全 索引
「Python系列」Python元组
Python中的元组(Tuple)是一种不可变的有序序列类型,它允许你存储多个不同类型的元素,并且这些元素在元组中是按照特定的顺序排列的。一旦一个元组被创建,你就不能修改它(即不能添加、删除或更改元组中的元素),这使得元组成为一种非常安全的数据结构,因为一旦它们被创建,就不
21 1
|
13天前
|
索引 Python
python元组内置方法知识
Python元组方法简介:`count()`统计元素出现次数,如`t.count(2)`返回3;`index()`获取元素首次出现的索引,如`t.index(3)`返回2;`insert(index, element)`在指定位置插入元素,如`t.insert(1, &#39;a&#39;)`;`remove(element)`删除元素,如`t.remove(2)`返回 `(1, 3)`;`pop()`删除并返回最后一个元素,如`t.pop()`返回3;`reverse()`反转元组元素,如`t.reverse()`后`t`变为`(3, 2, 1)`。
17 5
|
13天前
|
索引 Python 容器
python 数据类型之列表
python 数据类型之列表
|
16天前
|
索引 Python
Python标准数据类型-List(列表)
Python标准数据类型-List(列表)
42 1
|
21天前
|
存储 Java 程序员
【Python】6. 基础语法(4) -- 列表+元组+字典篇
【Python】6. 基础语法(4) -- 列表+元组+字典篇
41 1