Python数据类型
常见的6种
# 常用 数据类型 6 种
# str
name = "haha"
# number (int float)
a, b = 100, 99.9
# list 可以存不同类型的数组
ls = ["name", 110, 99.9, (222, 22), {"name": "eric"}]
# tuple 不能更改的list
t = (22, 333)
# dict
d = {"name":"zhangsan", "age":23}
# set 无序不重复
s = {222, 333, 33, 33, 333}
print(s)
字符串和数字
# str
name = "haha, xixi, hehe"
# 字符串一旦被创建, 不可变
# 常用方法
# 索引访问
print(name[3])
# len
print(len(name)) #4
# 替换
print(name.replace(",", "", 1))
# 分割字符串
print(name.split()) # ['haha,', 'xixi,', 'hehe']
print(name.split(",")) # ['haha', ' xixi', ' hehe']
# 列表变成字符串
print("_".join(["1", "2", "3", "4"]))
print("/".join(["1", "2", "3", "4"]))
print("*".join(["1", "2", "3", "4"]))
print("".join(["1", "2", "3", "4"]))
print(" ".join(["1", "2", "3", "4"]))
# slice 切片 列表也可以切片
# 对序列截取一部分的操作
names = "zhangsan lisi"
# 左闭右开
# names[start:end:step]
print(names[0:8]) #zhangsan
print(names[:8]) # zhangsan
print(names[0:8:1]) #zhangsan
print(names[9:]) #lisi
print(names[9:13]) #lisi
print(names[:])
print(names[::2])
print(id(names))
# 右侧开始
print(names[-4:])
# 反转
print(names[::-1])
# number (int float)
a, b = 100, 99.9
列表和元组
# list 可以存不同类型的数组
ls = ["name", 110, 99.9, (222, 22), {"name": "eric"}]
# 查询
print(ls[1])
print(len(ls))
# 增加
# 末尾追加
ls.append(["haha", "嘻嘻"])
print(ls)
ls.insert(1, "你好")
print(ls)
ls.extend(["haha", "嘻嘻"])
print(ls)
# 修改
ls[3] = "120"
print(ls)
# 删除
del ls[0]
print(ls)
print(ls.pop())
print(ls.pop(0))
print(ls)
# 列表推导式 (简化版的for循环)
# [表达式 for 临时变量 in 可迭代对象]
print([i for i in range(10)])
# li = []
# for i in range(10):
# li.append(i)
# print(li)
print([i + 10 for i in range(10)])
print([str(i) for i in range(10)])
print(["student" + str(i+1) for i in range(10)])
from random import randint
print([randint(40, 41) for _ in range(10)])
# 列表的迭代
# 模拟10个同学的成绩
score_ls = [randint(40, 100) for _ in range(10)]
print(score_ls)
# 选出及格的同学
# jige = []
# for score in score_ls:
# if score >=60:
# jige.append(score)
# print(jige)
print([i for i in score_ls if i >= 60])
# tuple 不能更改的list
t = (22, 333, [333, 444])
#index
print(t[0])
#
t[2][0] = 70 # TypeError: 'tuple' object does not support item assignment
print(t)
# 只有一个元素的元组
b = (99, )
print(type(b))
# 返回值类型是元组
for i in t:
print(i)
print(t[:2])
字典集合
# dict
d = {"name":"zhangsan", "age":23}
# key - value
print(d["name"])
# print(d["gender"])
print(d.get("name"))
print(d.get("gender"))
print(d.get("gender", "girl"))
# 修改
d["age"] = 55
print(d)
# 添加
d["gender"] = "girl"
print(d)
# 删除
# del d["age"]
# print(d)
# d.clear()
# print(d)
# 字典常用方法
print(len(d))
# 获取所有键
print(list(d.keys()))
# 获取所有值
print(list(d.values()))
# 获取所有键值
print(list(d.items())) # [('name', 'zhangsan'), ('age', 55), ('gender', 'girl')]
# # 字典的遍历
# for k in d.items():
# print(k)
# 字典的遍历
# 序列解包
# a, b, c = (122, 333, 444)
# print(a)
# print(b)
# print(c)
for k, v in d.items():
print(k, "-->", v)
# 字典推导式
print({i: i for i in range(10)})
print({str(i): i for i in range(10)})
import string
from random import randint
print(string.ascii_uppercase[:5])
print({k: randint(40, 60) for k in string.ascii_uppercase[:7]})
# # set 无序不重复
s = {222, 333, 33, 33, 333}
# print(s[0]) # 'set' object does not support indexing
print(s)
s.add(111)
s.add(222)
print(s)
# 遍历集合
for i in s:
print(i)
词频统计
text = "You Are My Sunshine The other night dear as I lay sleeping I dreamed I held you in my arms When I awoke dear I was mistaken and I hung my head and cri Y"
word_list = text.split()
print(word_list)
# {'You':3, ....}
counts = {}
# for word in word_list:
# counts[word] = 0
# for word in word_list:
# counts[word] = counts[word] + 1
for word in word_list:
counts[word] = counts.get(word, 0) + 1
print(counts)
排序
# 列表的排序
from random import randint
ls = [randint(1, 100) for _ in range(10)]
print(ls)
# # ls.sort()
# ls.sort(reverse=True)
# print(ls) #原地操作
# print(sorted(ls))
# print(ls)
# [{}, {}, {}]
stu_list = [
{"name": "zhangsan", "age": 108, "score": 88},
{"name": "lisi", "age": 38, "score": 28},
{"name": "wangwu", "age": 58, "score": 48},
{"name": "zhaoliu", "age": 98, "score": 58},
]
def sort_by_age(item):
return item["age"]
stu_list.sort(key=sort_by_age)
print(stu_list)
# [(), (), ()]
stu_list = [
("zhangsan", 108),
("lisi", 58),
("zhangsan", 108),
("zhaoliu", 58),
]
网友评论