文章目录
列表list
用方括号[ ]
可修改
索引index 访问列表元素
index
索引从0开始
索引为-1可以返回列表最后一个列表元素
fruit = ['apple','pear','banana']
print(fruit.index('apple')) # 0
修改列表元素index
列表名[index] = ‘新值’
fruit = ['apple','pear','banana']
fruit[1] = 'orange'
print(fruit) #['apple', 'orange', 'banana']
添加列表元素append,insert,
在末尾添加 append
列表名.append(‘新元素值’)
fruit.append('grape')
在列表中添加insert
列表名.insert(index,‘元素’) 在该index索引位置添加该元素
fruit = ['apple','pear','banana']
fruit.insert(0,'watermelon')
print(fruit) # ['watermelon', 'apple', 'pear', 'banana']
shucai = input()
myfruit = fruit + ['shuiguo'] + [shucai]
print(myfruit) # ['watermelon', 'apple', 'pear', 'banana','shuiguo']
删除列表元素del,pop,remove
del
del 列表名[index]
del fruit[1]
pop() 方法
默认删除列表末尾的元素(可以将删除的值赋值给其他变量)
括号内可传索引值
remove() 方法
删除元素值
fruit.remove('apple')
in 和 not in
print('apple' in fruit) # True
多重赋值
tom = ['cat','32','blue']
pinzhong,age,yanse = tom
print(pinzhong) # cat
列表排序
sort()方法 永久性排序(按字母排序)
按首字母在ASCII的值排序 ASCII 字符顺序
fruit = ['apple','pear','banana']
fruit.sort()
print(fruit) # ['apple', 'banana', 'pear']
>>> spam = ['a', 'z', 'A', 'Z']
>>> spam.sort(key=str.lower)
>>> spam
['a', 'A', 'z', 'Z']
向sort传递参数reverse = True,按Z~A排序
fruit.sort(reverse=True)
函数sorted() 临时排序
按字母顺序排序 可传递参数reverse=True
print(sorted(fruit))
print(sorted(fruit,reverse=True))
reverse()方法 按与原来列表相反的顺序排序
fruit = ['apple','pear','banana']
fruit.reverse()
print(fruit) # ['banana', 'pear', 'apple']
len()函数 获取列表的长度
len(列表名)
len(fruit)
遍历列表
for xxx in xxx:
min(),max(),sum()
squares = [value**2 for value in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
切片
索引
fruit[0:2]
fruit[:2] # 默认索引从0开始
fruit[1:] # 默认索引到列表末尾结束
fruit[-2:] # 最后两个
复制列表 可以创建一个包含整个列表的切片 即该列表的副本
myfruit = fruit[:]
元组tuple
用圆括号( )
不可修改
元组里若只有一个元素,该元素后面要跟上逗号 和字符串区分
>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>
tuple = (23,)
copy模块的copy(),deepcopy()函数
copy.deepcopy()函数 复制的列表中包含列表
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']
本文详细介绍了Python中列表的基本操作,包括通过索引访问和修改元素,使用append、insert方法添加元素,以及del、pop和remove函数删除元素。此外,还涵盖了列表的排序功能如sort、sorted和reverse,以及遍历、切片、元组和复制列表的知识,包括浅拷贝和深拷贝的概念。
6890

被折叠的 条评论
为什么被折叠?



