1、列表
在Python中,列表是一个有序且可更改的集合。是使用方括号 [] 进行编写的,列表的所有元素都放在方括号“[]”中,并使用逗号分隔开;列表中的元素数据类型可以不同,可以包含整数、浮点数、复数、列表、元组、字典、集合等。
1.1、创建列表
# 空列表
empty_list = []
# 或
empty_list = list()
# 非空列表
numbers = [1, 2, 3, 4, 5]
strings = ["apple", "banana", "cherry"]
mixed = [1, "apple", True, 3.14]
# 使用列表推导式创建列表
# 列表推导式创建列表的方法非常简洁,利用循环和表达式结合来生成列表
squares = [x**2 for x in range(10)]
# 使用list()函数创建列表
list1 = list(('apple', 'banana', 'cherry'))
注意:在使用list()函数创建列表时,一定要注意双括号,使用list函数,其实是把已创建的对象(例如字符串、元组、集合等)转换为列表
1.2、访问列表
1)、索引下标访问:列表中的元素是有序的,每个元素都有一个唯一的索引(下标)。可以通过下标来访问列表中的元素,下标访问列表分为两大类,正索引和负索引。正索引下标从0开始;负索引下标从-1开始。
'''
格式:列表名[下标] 例:list_name[i]
其中,list_name 是列表名,i是索引值。list_name[0]表示列表的第一个元素,list_name[-1]则表示列表的最后一个元素。
正向索引:list_name[0]、list_naem[1]...
反向索引:list_name[-1]、list_naem[-2]...
'''
# 使用下标索引访问
fruits = ["apple", "banana", "orange", "pear"]
# 正索引访问
print(fruits[0]) # 输出"apple"
print(fruits[1]) # 输出"banana"
print(fruits[2]) # 输出"orange"
print(fruits[3]) # 输出"pear"
# 负索引访问
print(fruits[-1]) # 输出"pear"
print(fruits[-2]) # 输出"orange"
print(fruits[-3]) # 输出"banana"
print(fruits[-4]) # 输出"apple"
2)、 切片访问:切片操作符用来访问列表中的一部分元素,返回从索引start到end-1的元素。
'''
格式:list_name[strat : end : step]
start: 表示起始索引
end: 表示结束索引
step: 表示步长
注意:在使用切片访问列表元素时,list_name[strat : end : step],[start:end] 是左闭右开区间,即访问不了 end 代表的元素。
'''
fruits = ["apple", "banana", "orange", "pear", "fig", "grape"]
print(fruits[1:4]) # 输出 ['banana', 'orange', 'pear']
print(fruits[:3]) # 输出 ['apple', 'banana', 'orange']
print(fruits[3:]) # 输出 ['pear', 'fig', 'grape']
print(fruits[::2]) # 输出 ['apple', 'orange', 'fig']
print(fruits[::-1]) # 输出 ['grape', 'fig', 'pear', 'orange', 'banana', 'apple']
3)、for循环遍历列表
fruits = ['apple', 'banana', 'orange', 'pear']
# for循环遍历
for i in fruits:
print(i)
'''
输出结果:apple
banana
orange
pear
'''
4)、检查元素是否存在:in,检查列表中是否存在某一项
# 检查列表中是否存在'pear'
fruits = ['apple', 'orange', 'pear', 'banana']
print('pear' in fruits)
# 输出: True
# 使用 in 关键字检查列表中是否存在指定项时,如果存在,返回 True ;反之,则返回 False
1.3、修改列表
列表是可变的,说明可以修改列表中的元素,可以通过索引下标来修改元素,也可以使用列表方法来操作列表
1)、修改单个元素
# 通过索引修改列表的单个元素
fruits = ['apple', 'banana', 'orange', 'pear']
fruits[1] = 'fig'
print(fruits)
# 输出 ['apple', 'fig', 'orange', 'pear']
2)、使用切片修改多个元素
# 使用切片操作符修改元素
fruits = ["apple", "banana", "pear", "fig"]
fruits[1:3] = ["orange", "grape"]
print(fruits) # 输出 ['apple', 'orange', 'grape', 'fig']
3)、使用列表方法修改列表:Python提供了很多列表内置方法来操作列表,包括添加、删除、排序等。
fruits = ["apple", "banana", "orange", "pear"]
# append() 方法在列表末尾添加一个元素
fruits.append("fig")
print(fruits) # 输出 ['apple', 'banana', 'orange', 'pear', 'fig']
# insert() 方法在指定位置插入一个元素
fruits.insert(1, "grape")
print(fruits) # 输出 ['apple', 'grape', 'banana', 'orange', 'pear', 'fig']
# remove() 方法删除第一个匹配的元素
fruits.remove("banana")
print(fruits) # 输出 ['apple', 'grape', 'orange', 'pear', 'fig']
# pop() 方法删除并返回指定位置的元素
popped_fruit = fruits.pop(2)
print(fruits) # 输出 ['apple', 'grape', 'pear', 'fig']
print(popped_fruit) # 输出 'orange'
# sort() 方法对列表进行排序
fruits.sort()
print(fruits) # 输出 ['apple', 'fig', 'grape', 'pear']
# reverse() 方法反转列表中的元素
fruits.reverse()
print(fruits) # 输出 ['pear', 'grape', 'fig', 'apple']
# extend() 方法用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
newlist = [1, 2, 3]
fruits.extend(newlist)
print(fruits) # 输出 ['pear', 'grape', 'fig', 'apple', 1, 2, 3]
1.4、列表内置方法详解
1)、append():用于在列表末尾添加一个新的元素
语法:list.append(element)
element:必需,任何类型(字符串、数字、对象等)的元素
# 添加列表
num = [1, 2, 3]
addlist = ['A', 'B', 'C']
num.append(addlist)
print(num)
# 输出 [1, 2, 3, ['A', 'B', 'C']]
2)、insert():用于将指定对象插入列表的指定位置
语法:list.insert(position, element)
position:必需, 数字,指定插入的位置
element:必需,元素,任何类型(字符串、数字、对象)
# 把列表words插入到列表num中
num = [1, 2, 3]
words = ['a', 'c']
num.insert(1, words)
print(num)
# 输出 [1, ['a', 'c'], 2, 3]
补充:append() 只能在末尾处添加元素或列表,insert() 可以在任意位置添加元素或列表。
3)、extend(): 用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
语法:list.extend(iterable)
iterable:必需, 任何可迭代对象(列表、集合、元组、字符串等)
# 添加字符串到列表末尾
num = [1, 2, 3]
str1 = 'Hello'
num.extend(str1)
print(num)
# 输出 [1, 2, 3, 'H', 'e', 'l', 'l', 'o']
4)、remove() :用于移除列表中第一个匹配的元素。
语法:list.remove(element)
element:必需, 要删除的任何类型(列表、数字、字符串等)的元素
# 删除元素3
num = [1, 3, 2, 8, 3]
num.remove(3)
print(num)
# 输出 [1, 2, 8, 3]
注意:当删除的元素在列表中存在多个时,默认删除第一次出现的那个。
5)、clear():用于清空列表
语法:list.clear()
# 清空列表
word = ['A', 'B', 'C']
word.clear()
print(word)
# 输出 []
6)、pop():用于移除列表中的一个元素(默认最后一个),并且返回该元素的值。
语法:list.pop(pos)
pos:可选,数字,指定需要删除的元素位置。默认为-1,删除最后一个
# 删除最后一个
fruits = ['apple', 'banana', 'orange']
fruits.pop()
print(fruits)
# 输出 ['apple', 'banana']
# 删除指定位置的元素
nums= [1, 2, 3, 4]
nums.pop(1)
print(nums)
# 输出 [1, 3, 4]
7)、index():用于从列表中找到某个值第一个匹配的索引
语法:list.index(element)
element:必需,任何类型(字符串、数字等)。要查询的值
# 查找32第一次出现的位置
nums = [78, 98, 54, 24, 32, 45, 32]
print(num.index(32))
# 输出 4
8)、count():用于返回列表中某个元素出现的次数
语法:list.count(value)
value:必需,任何类型(字符串、数字等)。要查询的值
# 统计2出现的次数
num = [2, 5, 6, 2, 3, 1, 2, 6]
print(num.count(2))
# 输出 3
9)、sort():用于对列表进行排序
语法:list.sort(reverse = True|False, key = myFunc)
reverse :可选,reverse = True对列表进行降序排序,默认reverse = False
key:可选,指定排序标准的函数
# 以字母顺序对列表进行排序
fruits = ['apple', 'fig', 'orange', 'pear', 'banana']
fruits.sort()
print(fruits)
# 输出 ['apple', 'banana', 'fig', 'orange', 'pear']
# 对列表进行降序排序
fruits1= ['orange', 'fig', 'pear', 'apple', 'banana']
fruits1.sort(reverse=True)
print(fruits1)
# 输出 ['pear', 'orange', 'fig', 'banana', 'apple']
# 按照值长度对列表进行排序
# 返回值的长度的函数:
def myfunc(e):
return len(e)
words = ['a', 'bb','dddd', 'ccc', '']
words.sort(key=myfunc)
print(words)
# 输出 ['', 'a', 'bb', 'ccc', 'dddd']
10)、reverse():用于反转列表元素
语法:list.reverse()
# 反转下列列表
num = [1, 2, 3, 4]
num.reserve()
print(num)
# 输出 [4, 3, 2, 1]
11)、copy():用于复制列表
语法:list.copy()
# 复制下列列表
fruits = [apple', 'pear', 'orange', 'fig']
new_f = fruits.copy()
print(new_f)
# 输出 [apple', 'pear', 'orange', 'fig']
2、元组
元组与列表类似,区别在于元组不可修改,列表可修改;元组使用小括号“()”, 列表使用中括号“[]”。
2.1、创建元组
# 创建元组
tuple1 = tuple((1,2,3)) # 使用tuple()函数创建
print(tuple1)
tuple2 = (1,2,3,4,5,6,7,8,9,10)
print(tuple2)
# 创建一个元素的元组
tuple3 = (100, )
print(tuple3[0])
# 输出
# (1, 2, 3)
# (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
# 100
注意:当创建的元组中只包含一个元素时,必须带逗号。如果不带逗号会将左右括号默认视为运算符。
2.2、访问元组
元组和列表一样,可以使用索引和切片的方式访问元素
1)、索引访问:元组使用索引访问的方式和列表一样,都有正索引和负索引
nums = tuple(25, 78, 45, 23, 65, 89)
# 使用索引访问元组中的某个元素
print(nums[3]) # 使用正索引 输出 23
print(nums[-4]) # 使用负索引 输出 45
2)、切片访问
'''
格式:tuplename[start:end:step]
start: 起始索引
end: 结束索引
step: 步长
'''
url = tuple("http://c.biancheng.net/shell/")
# 使用切片访问元组中的一组元素
print(url[9: 18]) # 使用正数切片
print(url[9: 18: 3]) # 指定步长
print(url[-6: -1]) # 使用负数切片
# 输出 ('b', 'i', 'a', 'n', 'c', 'h', 'e', 'n', 'g')
# 输出 ('b', 'n', 'e')
# 输出 ('s', 'h', 'e', 'l', 'l')
3)、使用推导式生成并访问元组对象
# 注意:推导式赋值后,元组中的元素并没有被同一生成,一直到访问到某个元素时,才会被及时生成
# 创建元组
tuple1 = (value for value in range(1, 11)
# 访问
# print(tuple1) 无输出
for i in tuple1:
print(i)
'''
输出
1
2
3
4
5
6
7
8
9
10
'''
2.3、修改元组
元组是不可变序列,元组的元素不可修改,所以只能创建新的元组去替代旧的元组;因此,也不能删除元组的某个元素,要删除,就要删除整个元组
# 替换整个元组
tup = (14, 2.5, -36, 94)
print(tup)
# 对元组进行重新赋值
tup = ('hello world',"李长林")
print(tup)
# 输出 (14, 2.5, -36, 94)
# 输出 ('hello world', '李长林')
#删除元组
tup1 = ('李长林',"下周要上班")
print(tup1)
del tup1
print(tup1)
# 输出 ('李长林',"下周要上班")
# 报错 NameError: name 'tup' is not defined
Python自带垃圾回收功能,会自动销毁不用的元组,所以一般不需要手动del来删除。另外, 可以通过连接多个元组的方式向元组中添加新元素。
# 使用+连接元组
tup1 = (12, 5, -20, 13)
tup2 = (2+10j, -50.1, 99)
print(tup1+tup2)
print(tup1)
print(tup2)
# 输出 (12, 5, -20, 13, (2+10j), -50.1, 99)
# 输出 (12, 5, -20, 13)
# 输出 ((2+10j), -50.1, 99)
元组和列表的区别:
元组:元组是静态数组,一旦创建,其元素不可修改,所以元组是一个不可变序列
列表:列表是动态数组,列表元素可以更改,包括修改元素值,删除插入元素,所以列表是可变序列
2.4、元组内置方法和函数
1)、len函数:返回元组里面元素的个数
2)、max函数:返回元组里面最大的元素
3)、min函数:返回元组里面最小的元素
4)、count(val)方法:计算元组中val元素的个数
5)、index(val,start = 0,stop):检测元素 val 是否在下标为 start、stop 的元素中,且返回其下标。如果 val 不在搜索的元组中,则返回 ValueError。