Python学习Day05
列表
创建列表
>>> [1,2,3]
[1, 2, 3]
>>> [1,2,3,"Python"]
[1, 2, 3, 'Python']
>>>
>>> a = [1, 2, 3, 'Python']
>>> print(a)
[1, 2, 3, 'Python']
>>>
序列
列表也是一个序列
>>> for each in a:
print(each)
1
2
3
Python
>>>
>>> a[0]
1
>>> a[1]
2
>>> a[3]
'Python'
>>>
len()函数
当一个列表的长度未知使,如何访问最后一个元素
>>> unknow = ["Life","is","short","you","need","Python"]
>>> length = len(unknow)
>>> unknow[length - 1]
'Python'
>>>
>>> unknow[-1]
'Python'
>>> unknow[-2]
'need'
列表切片
>>> rhyme = [1,2,3,4,5]
>>> rhyme[0:3]
[1, 2, 3]
>>> rhyme[3:5]
[4, 5]
>>> rhyme[2:]
[3, 4, 5]
>>> rhyme[:2]
[1, 2]
>>> rhyme[0:5:2]
[1, 3, 5]
>>> rhyme[::2]
[1, 3, 5]
>>>
>>> rhyme[::-2]
[5, 3, 1]
>>> rhyme[::-1]
[5, 4, 3, 2, 1]
列表的增删改查
增
append()
可在列表的末位添加一个指定的函数
>>> subjects = ["Chinese","Math"]
>>> subjects.append("English")
>>> subjects
['Chinese', 'Math', 'English']
extend()
允许直接添加一个可迭代对象
>>> subjects.extend(["Physics","Chemistry","Biology"])
>>> subjects
['Chinese', 'Math', 'English', 'Physics', 'Chemistry', 'Biology']
切片
>>> s[len(s):] = [6]
>>> s
[1, 2, 3, 4, 5, 6]
>>>
>>> s[len(s):] = [7,8,9,10]
>>> s
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
insert()
可将数据插入序列中的任意位置
这个方法中有两个参数,第一个参数是指定待插入的位置,第二个参数是指定待插入的元素
>>> s = [1,3,4,5]
>>> s
[1, 3, 4, 5]
>>> s.insert(1,2)
>>>
>>> s
[1, 2, 3, 4, 5]
删
remove()
>>> subjects = ["Physics","Chemistry","Biology","Science"]
>>> subjects
['Physics', 'Chemistry', 'Biology', 'Science']
>>> subjects.remove("Science")
>>> subjects
['Physics', 'Chemistry', 'Biology']
N.B.
- 如果列表中存在多个匹配元素,那么它只会删除第一个元素
- 如果指定的元素不存在,那么程序就会报错
pop()
该函数可以删除某个位置的函数,其参数就是元素的下标索引值
>>> subjects = ["Physics","Chemistry","English","Biology"]
>>> subjects
['Physics', 'Chemistry', 'English', 'Biology']
>>> subjects.pop(2)
'English'
>>> subjects
['Physics', 'Chemistry', 'Biology']
clear()
清空列表
>>> subjects
['Physics', 'Chemistry', 'Biology']
>>> subjects.clear()
>>> subjects
[]
改
>>> science = ["Physics","Chemistry","English"]
>>> science[2] = "Biology"
>>> science
['Physics', 'Chemistry', 'Biology']
>>>
>>> science
['Physics', 'Chemistry', 'Biology']
>>> science[1:] = ["Math","Astronomy"]
>>> science
['Physics', 'Math', 'Astronomy']
sort() and reverse()
如果序列中的元素均为数字,我们可以用sort()和reverse()函数分别将序列中的数字按从小到大和从大到小排列
reverse()也可将序列中的元素反转,不需要序列中的元素全为数字
>>> nums = [3,5,1,2,3,10,9,9]
>>> nums
[3, 5, 1, 2, 3, 10, 9, 9]
>>> nums.sort()
>>> nums
[1, 2, 3, 3, 5, 9, 9, 10]
>>> nums.reverse()
>>> nums
[10, 9, 9, 5, 3, 3, 2, 1]
>>>
>>> nums = [3,5,1,2,3,10,9,9]
>>> nums
[3, 5, 1, 2, 3, 10, 9, 9]
>>> nums.sort(reverse = True)
>>> nums
[10, 9, 9, 5, 3, 3, 2, 1]
查
count()
查找一个序列中某个元素出现的次数
>>> nums = [1,7,9,7,2,3,4,8,7,6,4]
>>> nums.count(3)
1
>>> nums.count(7)
3
>>>
index()
查找一个序列中某个元素的索引值
>>> subjects = ["Physics","Astronomy","Biology","Math","Chinese"]
>>> subjects.index("Biology")
2
>>> subjects.index("Chinese")
4
>>>
N.B.
-
如果有多个相同元素,那么index()的返回值是序列中的第一个元素 >>> nums = [1,2,3,1,5,4]
>>> nums.index(1)
0
-
index(x,start,end) 可以指定查找的开始和结束位置 >>> nums = [1,2,3,1,5,4]
>>> nums.index(1,2,5)
3
>>>
?
|