软件测试/测试开发丨学习笔记之列表、元组、集合

688

本文为霍格沃兹测试开发学社学员笔记分享
原文链接:ceshiren.com/t/topic/246…

1、列表 list

列表是一个有序且可更改的集合,并且是最常用的 Python 数据类型。在 Python 中,列表是使用方括号 [] 编写的。

1、创建

1.1 使用[ ]创建列表

  • 创建一个空列表
li = []
  • 创建一个非空列表
li = ['baidu', 'ali', 'test']

1.2 使用list()函数创建

list1 = list(('apple', 'banana', 'cherry'))

注意:在使用list()函数创建列表时,一定要注意双括号

2、切片和索引

2.1 下标

下标索引访问元组分为两大类,即正向索引和反向索引,格式为 list_name[i] ,其中,list_name 表示列表名,i表示索引值,i可以是正数(正向索引)也可以是负数(反向索引)。

可以得知,list_name[0]表示列表的第一个元素,list_name[-1]则表示列表的最后一个元素

list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']
print(list_name[0])
print(list_name[-1])

wzq
hxw

正向索引:从第一个(下标0)开始、第二个(下标1)…

反向索引:从倒数第一个(下标-1)、倒数第二个(下标-2)…

image.png

2.2 切片 [start: stop: step]

● start 值: 指示开始索引值,如果没有指定,则默认开始值为 0; ● stop 值: 指示到哪个索引值结束,但不包括这个结束索引值。如果没有指定,则取列表允许的最大索引值; ● step 值: 步长值指示每一步大小,如果没有指定,则默认步长值为 1。 ● 三个值都是可选的,非必填 在使用切片访问列表元素时,list_name[strat : end : step],[start:end] 是左闭右开区间,即访问不了 end 代表的元素。

image.png

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(li[:5:2])   #从0开始,到第5个,然后步长为2,因为是前闭后开原则,所以下标为5的不选
print(li[2:4])   #从2开始,到第4个,步长默认为1
print(li[:4])    #从0开始,到第4个,步长默认为1
print(li[2:])
print(li[::2])
print(li[::-1])  #逆向打印

image.png

2.3 for循环遍历列表

可以使用for循环遍历列表中的项目:

list1 = ['apple', 'banana', 'test']
for i in list1:
    print(i)

apple
banana
test

2.4 检查项目是否存在

查看是否有指定项目,可以使用in关键字

list1 = ['apple', 'banana', 'test']
print('apple' in list1)

True

使用 in 关键字检查列表中是否存在指定项时,如果存在,则返回 True ;反之,则返回 False 。

2.5 更改列表值

当我们创建列表后,我们可以对列表中的数据项进行修改或更新,当然我们也可以使用 append() 方法来添加列表项。

fruit_list = ['apple', 'pear', 'cherry'] 
fruit_list[2] = 'banana' 
print(fruit_list) 

['apple', 'pear', 'banana']

注意:元组一旦创建后,其值将无法被更改,但是有其他解决方法。

2.6 列表连接(合并)/复制

与字符串一样,列表之间可以使用 + 号和 * 号实现元组的连接和复制,这就意味着它们可以生成一个新的列表。

1、+连接(合并)

x = [1, 2, 3] 
y = [4, 5, 6] 
print(x + y) 

[1, 2, 3, 4, 5, 6]

2、*复制

x = ['Hello'] 
print(x * 5) 

['Hello', 'Hello', 'Hello', 'Hello', 'Hello']

2.7 嵌套列表

使用嵌套列表即在列表里面创建其他列表

x = [1, 2, 3] 
y = ['a', 'b', 'c'] 
z = [x + y] 
print(z) 

[[1, 2, 3],['a', 'b', 'c']]

2.8 列表比较

列表比较需要引入 operator 模块的 eq 方法。

# 导入 operator 模块 
import operator 
a = [1, 2]
b = [2, 3] 
c = [2, 3] 
print("operator.eq(a, b):", operator.eq(a, b)) 
print("operator.eq(b, c):", operator.eq(b, c))

operator.eq(a, b): False 
operator.eq(b, c): True

3、内置函数

3.1 打印输出 print()

1、print()函数

print() 函数的功能我们已经非常熟悉了,就是打印输出。

my_list = ['aaa', 1.25, 12, True] 
print(my_list) 

['aaa', 1.25, 12, True]

3.2 确定列表项目 len()

2、len()函数

当我们要确定一个列表有多少项目(元素)时,可以使用len()函数。

my_list = ['aaa', 1.25, 12, True] 
print(len(my_list)) 

4

3.3 返回变量类型 type()

3、type()函数

使用 type() 函数可以确定变量是什么类型(字符串、列表、元组、字典或集合)。

info_list = ['name', 'gender', 'age', 'height', 'weight'] 
print(type(info_list)) 

<class 'list'>

当对info_list使用 type() 确定变量类型时,会返回<class 'list'>,表明这是一个列表。

3.4 转换为列表 list()

4、tuple()函数

tuple() 函数的功能是,将其他类型转换为元组类型,详细用法如下:

  • 将字符串转换为列表
str1 = 'Hello Python' 
print(list(str1)) 

['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
  • 将元组转换为列表
tuple1 = ('Hello', 'Python') 
print(list(tuple1)) 

['Hello', 'Python']
  • 将字典转换为列表
dict1 = {'Hello': 'Python', 'name': 'pink'} 
print(list(dict1)) 

['Hello', 'name']
  • 将集合转换为列表
set1 = {'Hello', 'Python', 'name', 'pink'} 
print(list(set1)) 

['Python', 'name', 'pink', 'Hello']
  • 将区间转换为列表
range1 = range(1, 6) 
print(list(range1)) 

[1, 2, 3, 4, 5]

3.5 元组元素最大/小值 max()、min()

5、max()函数和min()函数

max() 函数的作用是返回列表中元素最大值min() 函数的作用是返回列表中元素最小值

list1 = [4, 6, 2, 0, -5] 
print(max(list1)) 
print(min(list1)) 

list2 = ['a', 'z', 'A', 'Z'] 
print(max(list2)) 
print(min(list2)) 
6 -5 z A

3.6 删除列表 del

  • 删除单个元素

我们可以使用 del list_name[i] 来删除某个指定元素,其中 list_name 表示列表名,i 表示指定值的索引值。

list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance'] 
del list_de[1] 
print(list_de) 

['Baidu', 'Tencent', 'Bytedance']
  • 删除列表

del 函数不仅可以实现删除某个元素,还可以删除整个列表。

list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance'] 
del list_de

当我们使用 del 函数删除某列表后,再使用 print() 函数打印输出时,会报错NameError: name 'list_de' is not defined,表明该列表未被定义。

4、列表的方法

4.1 增加 append()、insert()、extend()

1、append()方法

append() 方法用于在列表末尾添加新的对象

# 添加元素
list1 = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']
list1.append('python')
print(list1)

# 添加列表
x = [1, 2, 3]
y = ['a', 'b', 'c']
x.append(y)
print(x)

['Baidu', 'Alibaba', 'Tencent', 'Bytedance', 'python']
[1, 2, 3, ['a', 'b', 'c']]

2、insert()方法

insert() 方法用于将指定对象插入列表的指定位置。

# 把值 “orange” 作为第二个元素插入 fruits 列表:
element = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']
element.insert(1, 'python')
print(element)

# 将列表 y 插入到列表 x 中
x = [1, 2, 3]
y = ['q', 'w', 'e']
x.insert(0, y)
print(x)

['Baidu', 'python', 'Alibaba', 'Tencent', 'Bytedance']
[['q', 'w', 'e'], 1, 2, 3]

append() 只能在末尾 处添加元素或列表,insert() 可以在任意位置 添加元素或列表。

3、extend()方法

extend() 方法用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。

li = []
li.extend('hogwarts')  # 添加的是字符串的所有字母
li.extend([1, 2, 3])  # 接收列表的所有元素
li.extend((4, 5, 6))  # 接收元组的所有元素
li.extend({'a': 1, 'b': 2})  # 接收字典的所有key值
print(li)

['h', 'o', 'g', 'w', 'a', 'r', 't', 's', 1, 2, 3, 4, 5, 6, 'a', 'b']

4.2 元素出现次数 count()

count()方法用于某个元素在列表中出现的次数

num = [1, 2, 5, 1, 4, 3, 6, 5, 1, 2, 6]
print(num.count(1))

3

4.3 指定值索引 index()

index() 方法用于从列表中找出某个值第一个匹配项的索引位置。

返回的是这个数字第一次出现的下标

num = [1, 2, 5, 1, 4, 3, 6, 5, 1, 2, 6]
print(num.index(5))

2

4.4 对列表排序 sort()

sort() 方法用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。

以字母顺序对列表进行排序:
words = ['apple', 'qwe', 'rrr', 'xfv', 'bgh']
words.sort()
print(words)
print(words.sort())

['apple', 'bgh', 'qwe', 'rrr', 'xfv']
None

对列表进行降序排序:
words.sort(reverse=True)
print(words)

words.sort(reverse=False)
print(words)

['xfv', 'rrr', 'qwe', 'bgh', 'apple']
['apple', 'bgh', 'qwe', 'rrr', 'xfv']

按照值的长度对列表进行排序:
def myfunc(e):
    return len(e)


words = ['a', 'bb', 'ccc', 'dddd', '']

words.sort(key=myfunc)
print(words)

['', 'a', 'bb', 'ccc', 'dddd']

根据字典的 “year” 值对字典列表进行排序:
def myfunc(e):
    return e['year']


words = [
    {'char': 'a', 'year': 1963},
    {'char': 'b', 'year': 2010},
    {'char': 'c', 'year': 2019}
]

words.sort(key=myfunc)
print(words)

[{'char': 'a', 'year': 1963}, {'char': 'b', 'year': 2010}, {'char': 'c', 'year': 2019}]

按照值的长度对列表进行降序排序:
# 返回值的长度的函数:
def myfunc(e):
    return len(e)

words = ['aa', 'b', 'ccc', 'dddd']

words.sort(reverse=True, key=myfunc)
print(words)

['dddd', 'ccc', 'aa', 'b']

指定列表中的元素排序来输出列表:
# 获取列表的第二个元素
def takeSecond(elem):
    return elem[1]

# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# 指定第二个元素排序
random.sort(key=takeSecond)

# 输出类别
print('排序列表:', random)

排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)]

4.5 复制列表 copy()

copy() 方法用于复制列表,类似于 a[:]

fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
print(x)

['apple', 'banana', 'cherry', 'orange']

复制(制作副本)的另一种方法是使用内置函数 list() ,如下:
list1 = ['apple', 'banana', 'cherry']
list_2 = list(list1)

4.6 颠倒列表顺序 reverse()

reverse() 方法用于反向列表中元素。

fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)

['cherry', 'banana', 'apple']

fruits = ['apple', 'banana', 'cherry'] fruits.reverse() print(fruits) ['cherry', 'banana', 'apple']

4.7 删除元素 pop()、remove()、clear()

1、pop()方法

pop() 方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

  • pos 未指定时,默认删除最后的元素
fruits = ['apple', 'banana', 'cherry']
fruits.pop()
print(fruits)

['apple', 'banana']
  • pos 指定要删除元素的位置
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)

['apple', 'cherry']

2、remove()方法

remove() 方法用于移除列表中某个值的第一个匹配项。

num = [1, 3, 2, 8, 3]
num.remove(3)
print(num)

[1, 2, 8, 3]

3、clear()方法

clear() 方法用于清空列表,类似于 del a[:]

clear() 方法的作用是清空列表,执行结束后对其使用 print() 打印输出时,会输出 [] ,说明列表还存在,只是空列表而已。

del 函数的作用是删除 列表,执行结束后对其使用 print() 打印输出时,会报错 NameError: name 'word' is not defined.。

word = ['A', 'B', 'C']
word.clear()
print(word)

[]

总结:

image.png

image.png