资讯>正文

列表数据类型的内置方法

来源:博客园 | 2023-09-09 14:12:17

列表数据类型的内置方法

1.作用

列表的作用就是可以描述多个值,就比如一个人可以有很多的爱好

2.定义方式

hobby_list = ["play", "swimming", "dancing"]print(hobby_list)lt = list("randysun")print(lt)

3.内置方法

优先掌握

  1. 索引取值


    (资料图)

    hobby_list = ["play", "swimming", "dancing"]print(hobby_list[-1])hobby_list[0] = "2233"print(hobby_list)print(hobby_list[::-1])
  2. 切片

    hobby_list = ["play", "swimming", "dancing"]print(hobby_list[:]) #输出:["play", "swimming", "dancing"]print(hobby_list[::-1]) #输出:["dancing", "swimming", "play"]
  3. 长度

    hobby_list = ["play", "swimming", "dancing"]print(len(hobby_list))获取hobby——list的长度 #输出:3
  4. in/not in

    hobby_list = ["play", "swimming", "dancing"]print("swimming" in hobby_list) #输出 True
  5. for循环

    hobby_list = ["play", "swimming", "dancing"]for hooby in hobby_list:    print(hooby) #依次输出hobby_list
  6. 删除del

    hobby_list = ["play", "swimming", "dancing"]del hobby_list #删除全部del hobby_list[-1] #删除从右往左第一个
  7. 追加

    hobby_list = ["play", "swimming", "dancing"]hobby_list.append("123") #在最后米娜追加print(hobby_list)

需要掌握

hobby_list = ["play", "swimming", "dancing", "1", "1"]
  1. 统计列表内某一个元素出现的次数

    print(hobby_list.count("")) #输出 0print(hobby_list.count("1")) #输出 2
  2. 扩展列表

    hobby_list.extend([1,2,3,4])print(hobby_list) #输出:["play", "swimming", "dancing", "1", "1", 1, 2, 3, 4]
  3. 清除

    print(hobby_list.clear()) #输出 []
  4. 复制列表

    hobby_list2 = hobby_list.copy()print(hobby_list2)
  5. 删除(默认删除最后一个)

    hobby_list.pop()print(hobby_list)
  6. 索引

    print(hobby_list.index("play"))print(hobby_list.index("play",2,4)) #索引2-4 内有没有该值
  7. 插入

    hobby_list.insert(0, "1") #索引0的位置插入字符1print(hobby_list)
  8. 移除(只会删除一个)

  9. 移除,只会删除一个

    hobby_list = ["play", "swimming", "dancing", "1", "1"]print(hobby_list)hobby_list.remove("1")print(hobby_list)
  10. 反转

    hobby_list.reverse()print(hobby_list)
  11. 排序

    hobb_list =  [1,0,45,120,77,3]hobby_list.sort()print(hobby_list00000000000000000000000.242.0000000000)

4.存一个值还是多个值

存在多个值

5.有序or无序

有序(可索引)

6.可变or不可变(重点)

可变

​可变:值变id不变

​不可变:值变id也变

lis = [1, 1, 2, 3, 4, 5]print(lis)print(id(lis))lis.append(100)print(lis)print(id(lis))
本文相关推荐
热门推荐
图片