列表
# list
# 列表可以存储不同类型的数据
names = ["蔡徐坤", "谢青芮", "李岩", 111, 88.8, [33, 444]]
print(names)
print(type(names))
# 列表的访问
print(names[0])
print(names[1])
print(type(names[1]))
print(names[5])
print(type(names[5]))
# 使用循环
print(len(names)) # 列表中元素的个数
for i in range(len(names)):
print(names[i])
# 修改
names[3] = "小明"
print(names)
# 增加
print("++++++++++++++++++++增加++++++++++++++++++++++")
# 末尾追加
names.append("小红")
names.append(["小张", "小王"])
print(names)
# 指定追加
names.insert(3, "小鹏")
print(names)
# 加入一个迭代对象, 会把迭代对象的每个元素一次追加到末尾
names.extend(["小李", "小丽"])
names.extend("哈哈哈")
print(names)
# 删除
names.remove("小鹏")
print(names)
# del names
# print(names) # NameError: name 'names' is not defined
del names[4]
print(names)
# 弹出指定元素 默认是 最后一个, 可以指定索引
print(names.pop())
print(names.pop())
print(names.pop())
print(names.pop())
print(names.pop(0))
print("pop = ", names)
列表操作
from random import randint
# 使用循环创建列表中的数据
# [0, 1, ...9]
li = []
for i in range(20, 31):
li.append(i)
print(li)
# 生成一个班的随机成绩
li2 = []
for _ in range(10):
score = randint(40, 100)
li2.append(score)
print(li2)
# 列表的遍历
for score in li2:
print(score, "\t", end='')
print()
for i in range(len(li2)):
print(li2[i], "\t", end='')
print()
# 筛选及格的同学
li3 = []
for score in li2:
if score >= 60:
li3.append(score)
print(li3)
li4=[]
for score in li2:
if score %2==0:
li4.append(score)
print(li4)
列表推导式
from random import randint
# [表达式 for 临时 in 迭代对象 if 条件]
print([i for i in range(10)])
print([i+100 for i in range(10)])
ls = [randint(40, 100) for _ in range(10)]
print(ls)
print([score for score in ls if score >=60])
print([score for score in ls if score %2==0])
# 求最大值
ls2 = [randint(1, 100) for _ in range(10)]
print(ls2)
max = ls2[0]
for num in ls2:
if num > max:
max = num
print("max = {}".format(max))
print("max = ", max)
元组
names = ["蔡徐坤", "谢青芮", "李岩", 111, 88.8, [33, 444]]
a = ("蔡徐坤", "谢青芮", "李岩", 111)
print(a)
print(type(a))
# 区别在于元组一旦创建不可以更改
# 访问
print(a[0])
print(a[1])
# 尝试修改
# a[4] = 1000 # TypeError: 'tuple' object does not support item assignment
# 列表和元组的转化
b = tuple(names)
print(b)
print(type(b))
c = list(b)
print(type(c))
# 遍历元组
for i in a:
print(i)
# 只有一个元素的元组
d = (111, )
print(d)
print(type(d))
字符串
import string
name = 'Python Java C++ '
# 单引号和双引号都行
# 字符串的长度
print(len(name))
# 访问
print(name[0])
# 迭代
print([i for i in name])
# for i in name:
# print(i)
print(string.ascii_uppercase)
print(type(string.ascii_uppercase))
print(string.ascii_lowercase)
print(string.ascii_letters)
letters = string.ascii_uppercase
print(letters)
# 切片 slice 对序列截取一部分的操作 字符串/列表/元组都支持
# 序列名[start: end :step] 左闭右开
print(letters[0:4])
print(letters[:4])
print(letters[2:6])
print(letters[2:])
print(letters[:])
print(letters[::2])
print(letters[::3])
print(letters[::-1])