首页 > 编程语言 >Python 每天一个知识点(预计为期100天)第一天

Python 每天一个知识点(预计为期100天)第一天

时间:2023-01-03 13:45:13浏览次数:42  
标签:知识点 Python list 元素 list1 列表 print 100 list2

列表的基本操作:

一,列表的定义:

  1.列表之内的元素不要求同一类型,所以极为方便

  2.列表的本质上是容器,最常见的是包含字符串,数字,自定义的对象

  3.根据不同编译器,list相邻元素未必是靠在一起的

list = ['123','12321da','dfffff'] 
list1 = ['123','12321da','fsfas'] 
list2 = ['123','1sad','rfewewe'] 

二,索引:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
# 自然数索引,从前往后,第一个是0
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
# 支持负数索引,从后往前,最后一个是-1
list[-1]
# 直接打印列表
fruits = ['grape', 'apple', 'banana', 'orange', 'pear'] # 打印的结果就是这一行
print('Before modify:\nfruits = '+str(fruits))
View Code

三,列表更新:

list = ['Google', 'Runoob', 1997, 2000]
 
print ("第三个元素为 : ", list[2])
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2])
 
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)

四,列表新增:

list1 = ['Google', 'Runoob', 1997, 2000]
list2 = ['Google', 'Runoob', 1997, 2000]
# append在末尾插入一个元素
list1.append('obj')
# 在指定位置之后插入元素,比如2就是在位置为2元素后面插入到3的位置(从零开始)。
list2.insert(2, 'watermelon')
# extend,把list2的内容结合在list1的末尾,最终形成一个列表
list1.extend(list2)
# 和上面等效
list3 = list1+list2

五,列表删除:

list1 = ['Google', 'Runoob', 1997, 2000]
 
print("原始列表 : ", list1)
del list[2]
print("删除第三个元素 : ", list1)
# pop,删除最后一个并返回
last = list1.pop()
# remove,注意元素一定要存在,而且只会删除第一个匹配到的
list1.remove('Google')

# 清空,会变成[]
list1.clear()

六,列表在函数中的操作:

m = [1,2,3,4,5,6,7]
# 统计该元素的个数
print(m.count(1))
# index,返回的是第一个匹配到的元素的的位置
print(m.index(1))
# 后面的参数划定了搜寻范围
print(m.index(3,2,5))
# sort,默认由大到小
print(m.sort())
print(m.sort(reverse=True))# 由小到大
# max
print(max(m))
# min
print(min(m))
#len
print(len(m))
# 列表的比较,可以自行深入研究
# 导入 operator 模块
import operator

a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b)) # False
print("operator.eq(c,b): ", operator.eq(c,b)) # True

七,列表的拷贝:

# 深拷贝
list1 = [1,2,3,4,5]
list2 = list1[:]
#或者
import copy # 需要特定的包
list3 = list1.deepcopy()
# 浅拷贝
list4 = list1
list5 = list1.copy() # 自带的方法是浅拷贝

八,列表的生成和遍历

a = [i for i in range(10)]

b = [1 for i in range(10)]

c = [1]*10
d = []*10 # 不会自动添加null
e = [[]]*10
print(a,b,c,d,e)

# 遍历
a = [1 for i in range(10)]
for i in a:
    print(i)

九,列表的差集交集和并集:

#两个列表的差集
# b中有而a中没有的 
list(set(b).difference(set(a))) 

#两个列表的并集
list(set(a).union(set(b)))

#两个列表的交集
list(set(a).intersection(set(b)))

 

标签:知识点,Python,list,元素,list1,列表,print,100,list2
From: https://www.cnblogs.com/slx-yyds/p/17021828.html

相关文章