python -- 列表

发布于 更新于

技术文章测试开发

一. 列表特性

一. 列表特性

  1. 有序

  2. 索引从0开始

  3. 数据可重复

  4. 元素的数据类型可以不一致

  5. 可以嵌套

  6. 可以迭代

  7. 可变

二、创建

  1. 变量名 = [值]

三、查询

  1. 通过索引查找元素

test_list = [1,2,3,4,5,6]
res = test_list[0]
print(res)
  1. 通过元素找索引 index 元素如果重复就返回第一个找到的元素的索引值

test_list = [1,2,3,4,5,6]
res = test_list.index(3)
print(res)
  1. 统计某个元素出现的次数 coun

test_list = [1,2,3,3,4,5,6]
res = test_list.count(3)
print(res)
  1. 查询长度 len

test_list = [1,2,3,3,4,5,6]
res = len(test_list)
print(res)
  1. 查询数据类型 type

test_list = [1,2,3,3,4,5,6]
res = type(test_list)
print(res)

四、列表切片

语法:test_list = [起始索引值 : 结束索引值 : 步长]

正序切片 倒序切片

注意点:

  1. 步长不写默认为1

  2. 结束索引不写默认是字符串的长度

  3. 起始值不写默认是0

  4. 索引的取值左闭右开(包含起始索引值,不包含结束索引值)

  5. 步长前面的为负(-)表示倒序切片,正(+)表示正序切片(+可以不写)

  6. 正序切片用正序索引,倒序切片用倒序索引

  7. 字符串中的空格也占一个索引位置

#正序切片
test_list = [1,2,3,3,4,5,6,"字符串"]
res = test_list[1:6]
print(res)
#倒序切片
test_list = [1,2,3,3,4,5,6,"字符串"]
res = test_list[-6:-1]
print(res)

五、修改列表:

  1. 通过索引值需改对应的元素

test_list = [1,2,3,3,4,5,6,"字符串"]
test_list[2] = 'A'
print(test_list)
  1. 最加写入元素(列表末尾)append

test_list = [1,2,3,3,4,5,6,"字符串"]
test_list.append('ABCD')
print(test_list)
  1. 插入到某个位置 insert

test_list = [1,2,3,3,4,5,6,"字符串"]
test_list.insert(1,'ABCD')
print(test_list)
  1. 列表合并 +加号

test_list = [1,2,3]
test_list1 = [4,5,6,"字符串"]
print(test_list+test_list1)

六、删除

  1. 通过索引删除对应的元素 pop 可以返回对应的值

test_list = [1,2,3,4,5,6,"字符串"]
test_list.pop(2)
print(test_list)
  1. 通过索引删除对应的元素,没有返回值 del

test_list = [1,2,3,4,5,6,"字符串"]
del test_list[2]
print(test_list)
  1. 通过索引值移除元素 remove

test_list = [1,2,3,4,5,6,"字符串"]
test_list.remove(1)
print(test_list)
  1. 清空列表 clear

test_list = [1,2,3,4,5,6,"字符串"]
test_list.clear()
print(test_list)

七、成员运算 in not in

test_list1 = [1,2,2,2,3,4,"字符串",[1,2,3]]
print(2 in test_list1)
print(2 not in test_list1)

八、排序

  1. 升序跑排 reverse = False

#升序跑排
test_list = [1,2,3,7,4,5,6]
test_list.sort(reverse=False)
print(test_list)
  1. 降序跑排 reverse = True

#降序跑排
test_list = [1,2,3,7,4,5,6]
test_list.sort(reverse=True)
print(test_list)

九、反转 reverser

test_list = [1,2,3,7,4,5,6]
test_list.reverse()
print(test_list)

十、其他方法

  1. 最大值 max

test_list = [1,2,3,7,4,5,6]
res = max(test_list)
print(res)
  1. 最小值 min

test_list = [1,2,3,7,4,5,6]
res = min(test_list)
print(res)
  1. 求和 sum

test_list = [1,2,3,7,4,5,6,1]
res = sum(test_list)
print(res)
  1. 长度 len

test_list = [1,2,3,7,4,5,6,1]
res = len(test_list)
print(res)

来源:testingpai

继续阅读