列表(list)
如何获取变量是否是列表类型的值?
print(type(变量名/值))
列表举例:
a=[1,'hello',(2,3),3.5,['python','hello']]
特点:
1:列表的数据类型可以是任何类型,如:数值型、字符串型、元组型、列表型等
2:列表使用中括号包含元素(元素之间是用逗号,隔开而非括号)
3:列表中,可以包含列表类型元素
4:如果列表中只有一个数据,它仍然是列表,如:L=[2]
5:列表的取值,同字符串的取值,元素的索引从0开始,有倒序和正序之分,分单个取值、多个取值
6:列表支持对元素进行增删改
列表的增:
语法1:
列表名.append(value)
特点:
默认增加在最后
每次只能增加一个元素 增加到指定位置,需先取后加
语法2:
列表名.insert(索引位置,value)
注: 每次只能增加一个值 insert不会报索引的错误
列表的删:
语法1:
列表名.clear()
语法2:
列表名.pop()
特点:
每次只能删除一个元素,且默认删除最后一位
列表的改:
特点:
等号直接赋值 用赋值符号= 进行重新赋值修改
列表的取值
举例1:
# 列表 b=[1,'hello',(2,3),3.5,'python']
print(b[1]) #取hello print(b[1][-1]) #取hello里的最后一位字母 p
rint(b[-1][4]) #取最后一个元素python里的o
print(b[-1][3]) #取最后一个元素python里的h
输出结果:
hello
o
o
h
举例2:
c=[1,'hello',(2,3),3.5,[1]]
print(c[-1]) #取c中的最后的元素
print(c[-1][0]) #取最后一个元素的第一个值
输出结果:
[1]
1
注:输出整个元素,是包括整个元素的类型输出;输出元素中的某个值或多个值,是输出元素中的具体的值。
举例3:
d=[1,'hello',(2,3),3.5,['python','hello']]
print(d) #输出整个列表
print(d[-1]) #取d中的最后的元素
print(d[-1][0]) #输出最后一个元素中的第一个值
print(d[-1][0][-1]) #输出最后一个元素中的第一个值中的最后一个值
输出结果:
[1, 'hello', (2, 3), 3.5, ['python', 'hello']]
['python', 'hello']
python
n
列表的增删改举例
举例:
d=[1,'hello',(2,3),3.5,['python','hello']]# 增
# 用append
d.append('liebiao')
print(d) #在最后加入liebiao
d[-2].append('lingling')
print(d) #在索引为-2的位置增加lingling
#在任意一位插入,用insert
d.insert((1),'rigth')
print(d) #在索引为1的插入rigth,其它往后顺序后延一位
d[-2].insert((1),'rigth')
print(d) #在索引为-2的元素上插入
d.insert((0),"lingling")
print(d) #在第一位元素上插入,其它往后延一位
输出结果:
[1, 'hello', (2, 3), 3.5, ['python', 'hello'], 'liebiao']
[1, 'hello', (2, 3), 3.5, ['python', 'hello', 'lingling'], 'liebiao']
[1, 'rigth', 'hello', (2, 3), 3.5, ['python', 'hello', 'lingling'], 'liebiao']
[1, 'rigth', 'hello', (2, 3), 3.5, ['python', 'rigth', 'hello', 'lingling'], 'liebiao']
['lingling', 1, 'rigth', 'hello', (2, 3), 3.5, ['python', 'rigth', 'hello', 'lingling'], 'liebiao']