- 增加
hero_list = ["小鲁班", "安琪拉", "后羿", "妲己", "安琪拉"]
print(hero_list)
# 列表的增加
# append 在末尾进行追加
hero_list.append("云樱")
hero_list.append("云樱")
hero_list.append(["澜", "瑶"])
hero_list.append(11)
print(hero_list)
# insert
hero_list.insert(1, "狄仁杰")
print(hero_list)
# extend 将序列拆分进行追加
hero_list.extend(["澜", "瑶"])
hero_list.extend("上官婉儿")
print(hero_list)
- 删除
# del hero_list
# print(hero_list) # NameError: name 'hero_list' is not defined
# del hero_list[9]
# del hero_list[0]
# print(hero_list)
hero_list.clear()
print(hero_list) # []
列表的操作
# 快速创建列表
from random import randint
li = [] # 空列表
for i in range(10):
li.append(i)
print(li)
# 指定随机数的列表
score_list = [] # 空列表
for _ in range(10):
num = randint(50, 100) # [左闭右闭]的随机值
score_list.append(num)
print(score_list)
# 遍历(一个一个取出) [迭代]列表
jige_list = []
for score in score_list:
if score > 60:
jige_list.append(score)
print(jige_list)
# 求出列表中成绩最高的
max_score = score_list[0] # 假设列表的第一个值是最大的
for score in score_list:
if score > max_score:
max_score = score
print(max_score)
# 求出及格学生中成绩是偶数的
odd = []
for score in jige_list:
if score%2==0:
odd.append(score)
print(odd)
列表推导式
简化了for 循环
[表达式 for 临时变量 in 迭代对象 if 条件]
# 快速创建列表
from random import randint
print([i for i in range(10)])
print([i + 10 for i in range(10)])
print([i**2 for i in range(10)])
# 指定随机数的列表
score_list = [randint(40, 100) for _ in range(10)]
print("score_list = ", score_list)
jiege = [i for i in score_list if i > 60]
print("及格", jiege)
# # 求出及格学生中成绩是偶数的
print([i for i in jiege if i%2==0])
元组
# 元组 不能修改的的列表
hero_list = ["小鲁班", "安琪拉", "后羿", "妲己", "安琪拉"]
t = tuple(hero_list)
print(t)
print(type(t))
# 访问
print(t[0])
# t[0] = "大鲁班" # TypeError: 'tuple' object does not support item assignment
for x in t:
print(x)
字符串
# 字符串 '' "" 包裹的就是字符串
# 不可变性: 字符串一旦被创建, 值是不变的
name = "Python Java C++"
# 下标访问
print(name[1])
# name[1] = "Y" # str' object does not support item assignment
# 字符串的遍历
print([i for i in name])
# 切片 : 对序列截取一部分的操作
# 变量名[start:end:step] 左闭右开
print(name[0:6]) # Python
print(name[0:6:1]) # Python
print(name[:6]) # Python
print(name[0:6:2]) # Pto
print(name[12:15])
print(name[12:])
print(name[:])
print(name[::])
# 步长是 负数代表 从右到左
print(name[::-1])
# 如果说从右边开始计索引 右面第一个值是 -1
print(name[-1])
print(name[14])
print(name[14:10:-1])
print(name[-1:-5:-1])
print(name[:8:2]) #
列表和元组同样支持切片
import string
print(string.ascii_uppercase)
print(string.ascii_lowercase)
print(string.ascii_letters)
ls = [i for i in string.ascii_uppercase[:8]]
print(ls)
# 列表的切片
print(ls[:4])
print(ls[::-1])
t = tuple(ls)
print(t[:4])
print(t[::-1])