列表相比于字符串,不仅可以存放不同的数据类型。而且可以存放大量的数据.32位python可以存放:64位可以存放:1152921504606846975个元素。而且列表是有序的(按照你保存的顺序)有索引,可以切片方便取值.
1.1 列表的索引和切片
列表和字符串一样也拥有索引:
Lst=["麻花藤","王剑林","马芸","周鸿医","向华强"]print(Lst[0]) # 获取第一个元素
print(lst[1])
print(lst[2])lst[3]="流动强” #注意,列表是可以发生改变的,这里和字符串不一样
print(Lst) #["麻花藤','王剑林',"马芸',"流动强','向华强']s0 = "向华枪"
s0[1] = "美" # TypeError: 'str' object does not support item assignment
print(s0)
列表的切片:
Lst=["麻花藤","王剑林","马芸","周鸿医","向华强"]
print(lst[0:3]) # ['麻花藤',王剑林',马芸]
print (lst[:3]) # ['麻花藤',王剑林’,"马芸']
print(Lst[1::2]) # ['王剑林’,‘周鸿医']也有步长
print(lst[2::-1]) # ['马芸’,王剑林,'麻花藤’]也可以倒看取
1.2 列表的相关操作
1. 增加,注意,list 和 str 是不一样的,list可以发生改变, 你所以直接就在原来的对象上进行操作
lst = ["麻花藤","王剑林","马芸","周鸿医","向华强"]
print(lst)
lst.append("wiss")
print(lst)lst = []
while 1:content = input("请输入员工信息,输入Q退出:")if content.upper() == "Q":print("退出,,,\n请再次输入,,,")breaklst.append(content)print(lst)lst = ["麻花藤","王剑林","马芸","周鸿医","向华强"]
lst.insert(2,"刘德华")
print(lst)
2. 删除
pop , remove , clear , del
lst = ["麻花藤","王剑林","马芸","周鸿医","向华强"]
print(lst)
deleted = lst.pop() # 删除追后一个
print("被删除的",deleted)
print(lst)el = lst.pop(2) # 删除2号元素
print(el)
print(lst)lst.remove("王剑林") # 删除指定元素
print(lst)lst.clear() # 清空list
print(lst)# 切片删除
del lst[1:3]
print(lst)
3.修改
索引切片修改
lst = ["得儿得儿","太牛","胡辣汤","空间","腾格尔"]
lst[1] = "太污"
print(lst)lst[1:4:2] = ["马化腾","饥荒"]
print(lst)lst[1:4]=["交换空间"]
print(lst)
4.查询, 列表是一个可迭代对象,所以可以进行for循环
for er in lst:
print(el)
5.其他操作
lst = ["小白","小黑","小白","马总","小白","饥荒"]
c = lst.count("小白") # 查询出现的次数
print(c)lst = [1,54,154,12,23]
lst.sort()
print(lst)
lst.sort(reverse=True) # 降序
print(lst)lst = ["小白","小黑","小白","马总","小白","饥荒"]
print(lst)
lst.reverse()
print(lst)l = len(lst) # 列表的长度
print(l)
6.用range 循环出列表中的每一个元素的索引
lst = ["小白","小黑","小白","马总","小白","饥荒"]
for i in range(len(lst)):print(i,lst[i])
总结:
1.append()增加数据,insert
2.remove()删除数据
3.list[index]=value修改数据
4.for循环循环查看
本文链接:https://my.lmcjl.com/post/8819.html
展开阅读全文
4 评论