stu_info ={'name':'eric','age':19,'addr':'铁岭的',11:666}print(stu_info)# 获取字典中所有的键print(list(stu_info.keys()))# 获取字典中所有的值print(list(stu_info.values()))# 获取字典中所有的键 值 字典变成列表print(list(stu_info.items()))# 列表变成字典
ls =[('name','eric'),('age',19),('addr','铁岭的'),(11,666)]print(dict(ls))for k, v in stu_info.items():print(k,v)# 使用lenprint(len(stu_info))
字典推导式
from random import randint
import string
print(string.ascii_uppercase)print(string.ascii_uppercase[:7])# ABCDEFGprint(string.ascii_lowercase)print(string.ascii_letters)# {k: v for 临时 in 迭代对象}print([i for i inrange(10)])print({i:1for i inrange(10)})print({1: i for i inrange(10)})print({i: i for i inrange(10)})print({str(i): i for i inrange(10)})print({6:6for i inrange(10)})print([i for i in"ABCDEFG"])print([i for i in string.ascii_uppercase[:7]])print([f'student{i}'for i in string.ascii_uppercase[:7]])# 学生做key 成绩做value
score_d={f'student{i}': randint(30,100)for i in string.ascii_uppercase[:7]}print(score_d)print({x for x in score_d})print({x for x in score_d.items()})print({x[0]:x[1]for x in score_d.items()})print({x[1]:x[0]for x in score_d.items()})print([i for i in[111,222,3333]if i >221])#选出字典中成绩大于 60的print({ k: v for k,v in score_d.items()if v >=60})
字符串常用方法
import string
# 字符串常用方法# '' 和 " " 声明的 支持切片# 字符串迭代# for i in "JiazhenLi":# print(i)print(list("JiazhenLi"))
name ="Python C++ Java"
path ='C:/Users/Eric/Documents'# 1.字符串 分割 --> 列表 默认按照空格分割print(name.split())print(name.split('+'))print(path.split('/'))print(path.split())# 2.去两端空格
name =" Python C++ Java "print(len(name))
name = name.strip()print(len(name))# 3.替换
price ='$9.9'
price = price.replace("$","")print(price)
price =float(price)
price =10*price
print(price)print([222,111]*3)# 4. join 列表变成字符串print("".join([str(i)for i in[111,222,333,444]]))print(" ".join([str(i)for i in[111,222,333,444]]))print("/".join([str(i)for i in[111,222,333,444]]))print("_".join([str(i)for i in[111,222,333,444]]))print([i for i in string.ascii_uppercase[:8]])print("_".join(string.ascii_uppercase[:8]))
词频统计
text ="When you face the world alone, alone When you face the world alone, When you face the world alone"
text = text.replace(",","")
word_list = text.split()print(word_list)# {"When": 4, "face":5}
counts ={}# for word in word_list:# counts[word] = 0# print(counts)for word in word_list:# counts[word] = counts[word] + 1
counts[word]= counts.get(word,0)+1print(counts)