1.1.2python基本数据类型之列表

点击跳转Python学习笔记总目录

一.列表 list

创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:

list1 = ['Google', 'python', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

1,访问列表中的值

使用下标索引来访问列表中的值

list1 = ['Google', 'python', 1997, 2000]
print(list1[0])
# 运行结果
Google
print(list2[1:5])
#运行结果
 [2, 3, 4, 5]

2,更新列表

list = ['Google', 'python', 1997, 2000]
print ("第三个元素为 : ", list[2])
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2])
#运行结果
2001

3,删除列表元素

list = ['Google', 'python', 1997, 2000]
print ("原始列表 : ", list)
del list[2]
print ("删除第三个元素 : ", list)
#运行结果
原始列表 :  ['Google', 'python', 1997, 2000]
删除第三个元素 :  ['Google', 'python', 2000]

4,Python列表截取与拼接

L=['Google', 'python', 'Taobao']
print(L[2])
# 运行结果
'Taobao'
print(L[-2])
#运行结果
'Runoob'
 print(L[1:]) #切片操作
 #运行结果
['Runoob', 'Taobao']

5,列表常用方法

常用函数:
1 len(list)
列表元素个数

li = [1,1,2,3,4]
n = len(li)
print(n)
输出:
5

2 max(list)
返回列表元素最大值

li = [1,1,2,3,4]
n = max(li)
print(n)
输出:
4

3 min(list)
返回列表元素最小值

li = [1,1,2,3,4]
n = min(li)
print(n)
输出:
1

4 list(seq)
将元组转换为列表

li = (1,1,2,3,4)
n = list(li)
print(n)
输出:
[1, 1, 2, 3, 4]

常用方法:
1 list.append(obj)
在列表末尾添加新的对象

li = [1,1,2,3,4]
li.append(5)
print(li)
输出:
[1, 1, 2, 3, 4, 5]

2 list.count(obj)
统计某个元素在列表中出现的次数

li = [1,1,2,3,4]
n=li.count(1)
print(n)
输出
2

3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

li = [1,1,2,3,4]
li.extend([5,6,7])
print(li)
输出
[1, 1, 2, 3, 4, 5, 6, 7]

4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置

li = [1,1,2,3,4]
n=li.index(3)
print(n)
输出:
3

5 list.insert(index, obj)
将对象插入列表

li = [1,1,2,3,4]
li.insert(0,3)
print(li)
输出
[3, 1, 1, 2, 3, 4]

6 list.pop([index=-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

li = [1,1,2,3,4]
li.pop(0)
print(li)
输出
[1, 2, 3, 4]

7 list.remove(obj)
移除列表中某个值的第一个匹配项

li = [1,1,2,3,4]
li.remove(3)
print(li)
输出
[1, 1, 2, 4]

8 list.reverse()
反向列表中元素

li = [1,1,2,3,4]
li.reverse()
print(li)
输出
[4, 3, 2, 1, 1]

9 list.sort(cmp=None, key=None, reverse=False)
对原列表进行排序

li = [9,1,1,2,3,4,0]
li.sort()
print(li)
输出
[0, 1, 1, 2, 3, 4, 9]

10 list.clear()
清空列表

li = [9,1,1,2,3,4,0]
li.clear()
print(li)
输出
[]

11 list.copy()
复制列表

li = [9,1,1,2,3,4,0]
new_li=li.copy()
print(new_li)
输出
[9, 1, 1, 2, 3, 4, 0]

猜你喜欢

转载自blog.csdn.net/weixin_39726347/article/details/86545995