Python入门篇之列表和元组
Jun 10, 2016 pm 03:19 PM列表和元组的主要区别在于,列表可以修改,元组则不能。一般情况下,在几乎所有的情况下列表都可以代替元组
例如:使用序列可以表示数据库中一个人的信息(姓名,年龄)
>>> 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'
View Code
运行结果:
>>>
Year: 1974
Month(1-12): 8
Day(1-31): 16
August 16th, 1974
分片
使用分片操作来访问一定范围内的元素,分片通过冒号相隔的两个索引来实现:
>>> tag='Python web site'
>>> 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,但是可以为负数,即从右往左提取元素
测试代码
序列相加
通过使用加号可以进行序列的连接操作:
>>> [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 "
[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、分片赋值
View Code
列表方法:
方法是一个与某些对象有紧密联系的函数,对象可能是列表、数字,也可能是字符串或者其他类型的对象,方法的调用方式:对象.方法(参数)
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 "
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 "
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')

Artikel Panas

Alat panas Tag

Artikel Panas

Tag artikel panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6
Alat pembangunan web visual

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Topik panas

Hasilkan PPT dengan satu klik! Kimi: Biarlah 'pekerja migran PPT' menjadi popular dahulu

Semua anugerah CVPR 2024 diumumkan! Hampir 10,000 orang menghadiri persidangan itu di luar talian dan seorang penyelidik Cina dari Google memenangi anugerah kertas terbaik

Google AI mengumumkan Gemini 1.5 Pro dan Gemma 2 untuk pembangun

Daripada logam kosong kepada model besar dengan 70 bilion parameter, berikut ialah tutorial dan skrip sedia untuk digunakan

Mengira 12 titik kesakitan RAG, arkitek kanan NVIDIA mengajar penyelesaian

AI sedang digunakan |. AI mencipta vlog kehidupan seorang gadis yang tinggal bersendirian, yang menerima berpuluh ribu suka dalam masa 3 hari

Bagaimana anda bertanya kepadanya Deepseek
