Python从入门到实践实操:3.列表
作者:互联网
建立表格并打印
bicycles = ["a","b","c"]
print(bicycles)
要求中括号以及逗号分隔
访问单个元素
bicycles = ["a","b","c"]
print(bicycles[0])
修改列表中的单个元素:
bicycles = ["a","b","c"]
print(bicycles[0])
bicycles[0] = "d"
print(bicycles)
添加:
.append()在末尾添加元素:bicycles = ["a","b","c"]
print(bicycles)
bicycles.append("d")
print(bicycles)
便可以在末尾加入
.insert(数位,)在第n位数
前面加入(从0计数):
bicycles = ["a","b","c"]
print(bicycles)
bicycles.insert(1,"d")
print(bicycles)
删除:
del ……[n]删除第几位:bicycles = ["a","b","c"]
print(bicycles)
del bicycles[0]
print(bicycles)
.pop()删除(栈原理:去掉最后一个)
bicycles = ["a","b","c"]
print(bicycles)
poped_bicycles = bicycles.pop()
print(bicycles)
print(poped_bicycles)
用途:如果列表元素按时间存储,该方法可以查找最后一个进入的元素
注意:
poped_bicycles = bicycles.pop()
是先执行了
poped_bicycles =
bicycles.
最后
再执行了
bicycles.pop()
举例:
bicycles = ["a","b","c"]
print(bicycles)
bicycles.pop()
poped_bicycles = bicycles.pop()
print(bicycles)
print(poped_bicycles)
.pop(n)可以弹出列表中的任意的第n个元素(注意的是
pop之后这个元素就不存在了)
.remove是删除值
bicycles = ["a","b","c"]
print(bicycles)
bicycles.remove("a")
print(bicycles)
但是只能删这个值第一个出现的元素
bicycles = ["a","a","b","c"]
print(bicycles)
bicycles.remove("a")
print(bicycles)
在应用场景中,我们还可以利用原因解释来说明remove的原因
bicycles = ["a","a","b","c"]
print(bicycles)
too_terrible="a"
bicycles.remove("a")
print(bicycles)
print(f"\nA {too_terrible} is too terrible for me")
记得输入字符变量需要
f和{}
列表的组织:
.sort永久的改变(回不去了),按字母排序bicycles = ["b","a","c"]
print(bicycles)
bicycles.sort()
print(bicycles)
倒序排
bicycles = ["b","a","c"]
print(bicycles)
bicycles.sort(reverse=True)
print(bicycles)
sorted(列表名)临时排序
bicycles = ["b","a","c"]
print(bicycles)
print(sorted(bicycles))
print(bicycles)
.reverse()倒置
bicycles = ["b","a","c"]
print(bicycles)
bicycles.reverse()
print(bicycles)
len(列表)确定列表长度,非常有用,用于确定还有多少个外星人未射杀(pop),确定需要管理多少项可视化数据,计算网站有多少注册用户
bicycles = ["b","a","c"]
print(bicycles)
print(len(bicycles))
输出列表最后一个元素(列表非空时),可以使用
bicycles[-1]
bicycles = ["b","a","c"]
print(bicycles)
print(bicycles[-1])
标签:入门,poped,Python,元素,pop,列表,bicycles,实操,print 来源: https://blog.csdn.net/tsdss_/article/details/118556846