Python 数据类型(3)------列表(list)
列表用来表示多个事物
users = ["张三","李四","王五"]
print(users)
一、列表公共功能
1.len
users = ["张三","李四","王五"]
v1 = len(users)
print(v1)
结果:3
2.索引
users = ["张三","李四","王五"]
v1 = users[1]
print(v1)
结果:李四
例99变66
user = ['abc','bcd','efg',99]
user[3] = 66
print(user)
print(user[2][1])
结果:['abc','bcd','efg',66]
f
3.切片
users = ["张三","李四","王五"]
v1 = users[0:2]
print(v1)
结果:张三,李四
4.步长
users = ["张三","李四","王五"]
v1 = users[0:2:2]
print(v1)
结果:张三
5.for循环
content = input('请输入:') #[5+9][ 5+9][5+ 9]
content_len = len(content)
index = 0
total = 0
while True:
char = content[index]
if char.isgigit():
total += int(char)
index += 1
if index == content_len:
break
方法二
content = input('请输入:') #[5+9][ 5+9][5+ 9]
result = content.split('+')
print(result)
v1 = int(result[0])
v2 = int(result[1])
v3 = v1 + v2
print(v3)
注:前后含有空格 int后直接去掉空格
例
users = ["张三","李四","王五"]
for i in users:
print(i)
结果: 张三
李四
王五
users = ["张三","李四","王五"]
for i in users:
for ele in i:
print(ele)
结果: 张
三
李
四
王
五
6.del
users = ['张三','李四','王五','张三']
del users[1]
print(users)
结果:['张三', '王五', '张三']
不支持对字符串直接删除(不可变类型),列表是可变类型
7.列表的嵌套
user = ['abc',0,True,[11,22,33,'aaa'],[1,['bbb','ccc'],2,3]]
User[3] = [11,22,33,'aaa']
User[3][3] = aaa
User[3][3][0] = a
例 列表的最后追加一个元素
users = []
while True:
name = input('请输入姓名:')
users.append(name)
print(users)
例 输入三次用户名密码
#录入用户名和密码
users = []
for i in range(0,3):
name = input('请输入用户名和密码')
users.append(name)
print(users) # ['张三,123','李四,888','王五,234']
#用户名和密码校验
username = input('请输入要登陆的用户名')
password = input('请输入要登陆的密码')
for item in users:
result = item.split(',') # ['张三','123']
user = result[0]
pwd = result[1]
if user == username and pwd == password:
print('登录成功')
break
2.insert 在指定索引位置插入元素
users = ['张三','李四','王五']
users.insert(1,'小黑')
print(users)
结果:['张三','小黑',李四','王五']
3.remove 删除元素
users = ['张三','李四','王五']
users.remove('李四')
print(users)
结果:['张三','王五'] #删除第一个匹配元素
4.pop 删除 默认删除最后一个
users = ['张三','李四','王五','张三']
users.pop(2)
print(users)
结果:['张三', '李四', '张三']
5.clear 清空
users = ['张三','李四','王五','张三']
users.clear()
print(users)
结果:[]
6.extend 扩展
#请将字符串 s = 'qwert'中的每一个元素追加到li列表中
li = ['张三','李四','王五','张三']
s = 'qwert'
li.extend(s)
print(li)
7.reverse( ) 排序 False(从小到大) True(从大到小)
v1 = [1,2,5,8,13,6,4,9]
print(v1)
v1.reverse()
print(v1)
结果: [1, 2, 5, 8, 13, 6, 4, 9]
[9, 4, 6, 13, 8, 5, 2, 1]
增
append/insert
删
remove/pop/del user[2]
改
user[2] = 新值
查
索引、切片