字典
# 字典
stu_info = {"name": "张三", "age": 15, "weight": 180, 100: 200}
print(stu_info)
print(type(stu_info)) # dict list tuple str int float
# key - value
# 访问 键访问值
print(stu_info["name"])
print(stu_info["age"])
print(stu_info["weight"])
print(stu_info[100])
# print(stu_info["gender"]) # KeyError: 'gender'
print(stu_info.get("name"))
print(stu_info.get("gender")) # None
print(stu_info.get("gender", "female")) # None
# 字典的修改
stu_info["name"] = "李四"
print(stu_info)
# 增加
stu_info["id"] = "12321321312"
print(stu_info)
# 删除
del stu_info["age"]
print(stu_info)
字典操作的方法
from sklearn import datasets
stu_info = {"name": "张三", "age": 15, "weight": 180, 100: 200}
# 获取所有键
print(list(stu_info.keys()))
print(datasets.load_boston().keys())
# 获取所有值
print(list(stu_info.values()))
# 获取所有键 - 值
print(list(stu_info.items()))
print(type(dict([('name', '张三'), ('age', 15), ('weight', 180), (100, 200)])))
print(dict([('name', '张三'), ('age', 15), ('weight', 180), (100, 200)]))
# 字典的遍历
# for v in stu_info.items():
# print(v)
for k, v in stu_info.items():
print(k,"--------->", v)
# 字典 使用 len 元素个数
print(len(stu_info))
词频统计
#
text = "You Are My Sunshine The other night dear as I lay sleeping I dreamed I held you in my arms When I aw You Are My Sunshine The other night dear as I lay s."
# 字符串分割成列表
word_ls = text.split()
print(word_ls)
# {"you":2, "My":4... }
counts = {}
# for word in word_ls:
# counts[word] = 0
# for word in word_ls:
# counts[word] = counts[word] + 1
for word in word_ls:
counts[word] = counts.get(word, 0) + 1
print(counts)
高级字典 pandas
import pandas as pd
s1 = pd.Series([1, 2, 3, 4])
print(s1[0])
s2 = pd.Series([1, 2, 3, 4], index=["a", "b", "c", "d"])
print(s2)
print(s2["a"])
print("++++++++++++++++++++++++++++++++++++++++++++++++++++")
# df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# print(df1)
df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["A", "B", "C"])
print(df1)
print(df1[:2])
print("++++++++++++++++++++++++++++++++++++++++++++++++++++")
print(df1["B"])
网友评论