标签:strong 注意 列表 报错 区别 分类 苹果 ext list()
数据类型的分类
可变(不可哈希)的:list dict set
不可变(可哈希)的:str bool int tuple
方法一:
l1 = [1,2,"哈哈哈"]
方法二:
li = list()
方法三:列表推导式
li = ["520","Python",123]
li.append("Faye")
print(li.append("append方法增加")) #不能打印它,结果是None
print(li)
li.insert(1,"哈哈哈") #按索引插入,把“哈哈哈”插入到索引为1的位置
print(li)
li.extend("ABC123") #extend是迭代增加
print(li)
None
['520', 'Python', 123, 'Faye', 'append方法增加']
['520', '哈哈哈', 'Python', 123, 'Faye', 'append方法增加']
['520', '哈哈哈', 'Python', 123, 'Faye', 'append方法增加', 'A', 'B', 'C', '1', '2', '3']
要特别注意extend和append的区别!
li = ["苹果","香蕉","菠萝"]
li.extend(["番茄","青菜"])
print(li)
li.append(["中国","上海"])
print(li)
['苹果', '香蕉', '菠萝', '番茄', '青菜']
['苹果', '香蕉', '菠萝', '番茄', '青菜', ['中国', '上海']]
#pop()
li = ["苹果","香蕉","菠萝","火龙果","西瓜","柿子"]
print(li.pop()) #默认删除最后一个元素
print(li.pop(2)) #按索引删
print(li)
柿子
菠萝
['苹果', '香蕉', '火龙果', '西瓜']
#remove()
li = ["苹果","香蕉","苹果","西瓜"]
li.remove("苹果")
print(li)
['香蕉', '苹果', '西瓜']
#clear
li = ["苹果","香蕉","苹果","西瓜"]
li.clear()
print(li)
[]
#del
li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"]
del li[3] #按索引删
print(li)
del li[::3] #按切片删
print(li)
del li #把这个li删了。print(li)会报错
['苹果', '香蕉', '菠萝', '西瓜', '水蜜桃', '橘子']
['香蕉', '菠萝', '水蜜桃', '橘子']
#直接改
li = ["苹果","香蕉","水蜜桃","橘子"]
li[-2] = "hhhh"
print(li)
['苹果', '香蕉', 'hhhh', '橘子']
#切片改
li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"]
li[2:] = "hh"
print(li)
['苹果', '香蕉', 'h', 'h']
如果要变成 li = ["苹果","香蕉","hh"] 怎么办呢?
#方法一:
li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"]
del li[2:]
li.append("hh")
print(li)
#方法二
li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"]
li[2:]=['hh']
li = ["苹果","香蕉","菠萝","苹果","西瓜","水蜜桃","橘子"]
print(li[-3])
print(li[::2])
西瓜
['苹果', '菠萝', '西瓜', '橘子']
标签:strong 注意 列表 报错 区别 分类 苹果 ext list()
原文地址:https://www.cnblogs.com/faye9898/p/11966291.html