本章介绍字典和集合数据结构,学习将数据结构存储为字典中的键值对、索引值、更改现有值、添加新键值对以及编写字典序列。接下来讨论如何将值存储为集合中的唯一元素,并执行常见的集合操作,例如并集、交集、差集和对称差集,还讨论了集合解析。最后对对象序列进行讨论,并介绍了Python pickle模块。
#1课程信息
def main():
values=[]
values.append(['3004','Haynes','8:00 a.m.'])
values.append(['4951','Alvarado','9:00 a.m.'])
values.append(['6755','Rich','10:00 a.m.'])
values.append(['1244','Burke','11:00 a.m.'])
values.append(['1411','Lee','1:00 p.m.'])
dic=dict()
dic['CS101']=values[0]
dic['CS102']=values[1]
dic['CS103']=values[2]
dic['NT110']=values[3]
dic['CM241']=values[4]
num=input("Please enter a course number:")
try:
print("According information is")
print("The teacher number is", dic[num][0])
print("The teacher name is", dic[num][1])
print("The time of course is", dic[num][2])
except KeyError:
print("The number is non-exist")
if __name__=="__main__":
main()
#2程序首府考试
import random
def main():
dic={'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little rock', 'California': 'Sacramento',
'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis',
'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta',
'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'St. Paul',
'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City',
'New hampshire': 'Concord', 'New jersey': 'Trenton', 'New mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg',
'Rhode island': 'Providence', 'South carolina': 'Columbia', 'South dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin',
'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston',
'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne', 'American Samoa': 'Pago Pago', 'Guam': 'Hagatna', 'Puerto Rico': 'San Juan',
'Northern Marianas': 'Saipan', 'U.S. Virgin Islands': 'Charlotte Amalie'}
problem=list(dic.keys())
i=random.randint(0,len(problem))
print(problem[i],'\'s state capital is ?',end='')
answer=input()
the_real=dic[problem[i]]
if the_real==answer:
print("you are right!")
else:
print("The answer is wrong.")
if __name__=="__main__":
main()
#3文件加密与解密
def encode(codes,path1,path2):
file1=open(path1,'r')
file2=open(path2,'w')
line1=file1.readline()
while line1!='':
line1=line1.strip()
res=''
for i in line1:
try:
ch=codes[i]
except KeyError:
ch=i
finally:
res+=ch
file2.write(res+'\n')
line1=file1.readline()
file1.close()
file2.close()
def decode(codes,path1):
print("The decode result:")
file1=open(path1,'r')
line1=file1.readline()
while line1!='':
line1=line1.strip()
res=''
for i in line1:
try:
ch=codes[i]
except KeyError:
ch=i
finally:
res+=ch
print(res)
line1=file1.readline()
file1.close()
def the_dictionary():
codes=dict()
index=33
for i in range(65,91):
codes[chr(i)]=chr(index)
codes[chr(index)]=chr(i)
index+=1
for i in range(97,123):
while index in codes:
index+=1
codes[chr(i)]=chr(index)
codes[chr(index)]=chr(i)
index+=1
return codes
def main():
codes=the_dictionary()
encode(codes,'normal.txt','to_encode.txt')
decode(codes,'to_encode.txt')
if __name__=="__main__":
main()
normal.txt内容:
to_encode.txt内容:
#4唯一单词
import re
def main():
file=open('draft.txt','r')
dic=dict()
line=file.readline()
while line!='':
line.rstrip('\n')
word=re.split(' |,',line)
#print(word)
for i in word:
if i=='':
continue
if i[-1]=='\n':
i=i[:-1]
if i[-1]=='.':
i=i[:-1]
i=i.lower()
if i not in dic:
dic[i]=1
else:
dic[i]+=1
line=file.readline()
file.close()
ans=[]
for i in dic:
if dic[i]==1:
ans.append(i)
print("The only word in the article includes:")
print(ans)
if __name__=="__main__":
main()
draft.txt的内容是特朗普先生的就职演讲稿,放在最后。
draft2.txt文本内容放在最后
#5单词频率
import re
def main():
file=open('draft.txt','r')
line=file.readline()
dic=dict()
while line!='':
line=line.strip()
word=re.split(',| ',line)
for i in word:
if i=='':
continue
if i[-1]=='\n':
i=i[:-1]
if i[-1]=='.':
i=i[:-1]
if i not in dic:
dic[i]=1
else:
dic[i]+=1
line=file.readline()
file.close()
for i in dic:
print(i," ",dic[i])
if __name__=="__main__":
main()
#6文件分析
import re
def get_set(path):
file=open(path,'r')
line=file.readline()
the_res=set()
while line!='':
line=line.strip()
res_lis=re.split(',| ',line)
for i in res_lis:
i=i.lower()
if i=='':
continue
if i[-1]=='\n':
i=i[:-1]
if i[-1]=='.':
i=i[:-1]
the_res.add(i)
line=file.readline()
file.close()
return the_res
def main():
set1=get_set('draft.txt')
set2=get_set('draft2.txt')
print("The only word that appears in two texts:")
print(set1.difference(set2))
print(set2.difference(set1))
print('Words that appear in both texts:')
print(set1.intersection(set2))
print("Word that appear only in the first of second file:")
print(set1^set2)
if __name__=="__main__":
main()
#8姓名与电子邮箱地址
import pickle
dic=dict()
def read_inf():
file=open('inf.dat','rb')
global dic
try:
dic=pickle.load(file)
except EOFError:
pass
file.close()
def save_inf():
file=open('inf.dat','wb')
pickle.dump(dic,file)
file.close()
def looking():
s=input("Please enter name you looking for:")
if s not in dic:
print("This person is non-exist")
else:
print(dic[s])
def adding():
s=input("Please enter name:")
s2=input("Please enter mail:")
if s in dic:
print("This one has existed")
else:
dic[s]=s2
save_inf()
def editing():
s=input("Please enter name:")
if s not in dic:
print("The name is non-exist")
else:
s2=input("Please enter this new mail:")
dic[s]=s2
save_inf()
def deleting():
s=input("Please enter name:")
if s not in dic:
print("The name is non-exist")
else:
del dic[s]
save_inf()
def main():
while True:
global dic
if len(dic)==0:
read_inf()
print("******-Looking for one's mail please enter 1-******")
print("******-Adding new name and mail please enter 2-******")
print("******-Editing mail please enter 3-******")
print("******-Deleting a name and mail please enter 4-******")
print("******-Exit this system please enter 0-******")
try:
choice = int(input())
if choice<0 or choice>4:
print("You enter is wrong")
else:
if choice==0:
break
else:
if choice==1:
looking()
elif choice==2:
adding()
elif choice==3:
editing()
elif choice==4:
deleting()
except ValueError:
print("You enter is wrong")
if __name__=="__main__":
main()
#10单词索引
def main():
file=open('Kennedy.txt','r')
file2=open('index.txt','w')
dic=dict()
line1=file.readline()
index=1
while line1!='':
line1=line1.strip()
lis=line1.split(' ')
for i in lis:
if i in dic:
dic[i].append(index)
else:
temp= [index]
dic[i]=temp
line1=file.readline()
index+=1
file.close()
for i in dic:
s=i+":"
for j in dic[i]:
s+=(' '+str(j))
file2.write(s+'\n')
file2.close()
if __name__=="__main__":
main()
draft.txt:
Chief Justice Roberts, President Carter, President Clinton, President Bush, President Obama, fellow Americans and people of the world, thank you.
We, the citizens of America, are now joined in a great national effort to rebuild our country and restore its promise for all of our people. Together we will determine the course of America and the world for many, many years to come.
We will face challenges. We will confront hardships. But we will get the job done. Every four years, we gather on these steps to carry out the orderly and peaceful transfer of power.
And we are grateful to President Obama and First Lady Michelle Obama for their gracious aid throughout this transition. They have been magnificent. Thank you.
Today’s ceremony, however, has very special meaning. Because today, we are not merely transferring power from one administration to another or from one party to another.
But we are transferring power from Washington D.C. and giving it back to you, the people.
For too long, a small group in our nation’s capital has reaped the rewards of government while the people have borne the cost. Washington flourished, but the people did not share in its wealth. Politicians prospered, but the jobs left. And the factories closed.
The establishment protected itself but not the citizens of our country. Their victories have not been your victories. Their triumphs have not been your triumphs. And while they celebrated in our nation’s capital, there was little to celebrate for struggling families all across our land. That all changes starting right here and right now. Because this moment is your moment. It belongs to you.
It belongs to everyone gathered here today and everyone watching all across America. This is your day. This is your celebration. And this, the United States of America, is your country.
What truly matters is not which party controls our government but whether our government is controlled by the people. January 20th, 2017 will be remembered as the day the people became the rulers of this nation again.
The forgotten men and women of our country will be forgotten no longer.
Everyone is listening to you now. You came by the tens of millions to become part of a historic movement, the likes of which the world has never seen before.
At the center of this movement is a crucial conviction – that a nation exist to serve its citizens. Americans want great schools for their children, safe neighborhoods for their families and good jobs for themselves.
These are just and reasonable demands of righteous people and a righteous public. But for too many of our citizens, a different reality exist. Mothers and children trapped in poverty in our inner cities, rusted out factories scattered like tombstones across the landscape of our nation, an education system flushed with cash but which leaves our young and beautiful students deprived of all knowledge. And the crime, and the gangs, and the drugs that have stolen too many lives and robbed our country of so much unrealized potential. This American carnage stops right here and stops right now.
We are one nation, and their pain is our pain. Their dreams are our dreams, and their success will be our success. We share one heart, one home and one glorious destiny.
The oath of office I take today is an oath of allegiance to all Americans. For many decades, we’ve enriched foreign industry at the expense of American industry, subsidized the armies of other countries while allowing for the very sad depletion of our military.
We defended other nation’s borders while refusing to defend our own.
And spent trillions and trillions of dollars overseas while America’s infrastructure has fallen into disrepair and decay.
We’ve made other countries rich while the wealth, strength, and confidence of our country has dissipated over the horizon. One by one, the factories shuttered and left our shores with not even a thought about the millions and millions of American workers that were left behind.
The wealth of our middle class has been ripped from their homes and then redistributed all across the world.
But that is the past and now we are looking only to the future.
We assembled here today are issuing a new decree to be heard in every city, in every foreign capital and in every hall of power. From this day forward, a new vision will govern our land. From this day forward, it’s going to be only America first – America first.
Every decision on trade, on taxes, on immigration, on foreign affairs will be made to benefit American workers and American families. We must protect our borders from the ravages of other countries making our products, stealing our companies and destroying our jobs.
Protection will lead to great prosperity and strength. I will fight for you with every breath in my body. And I will never, ever let you down.
America will start winning again, winning like never before.
We will bring back our jobs. We will bring back our borders. We will bring back our wealth, and we will bring back our dreams. We will build new roads and highways and bridges and airports and tunnels and railways all across our wonderful nation. We will get our people off of welfare and back to work rebuilding our country with American hands and American labor. We will follow two simple rules – buy American and hire American.
We will seek friendship and goodwill with the nations of the world.
But we do so with the understanding that it is the right of all nations to put their own interests first. We do not seek to impose our way of life on anyone but rather to let it shine as an example. We will shine for everyone to follow.
We will reinforce old alliances and form new ones. And unite the civilized world against radical Islamic terrorism, which we will eradicate completely from the face of the earth.
At the bedrock of our politics will be a total allegiance to the United States of America and through our loyalty to our country, we will rediscover our loyalty to each other. When you open your heart to patriotism, there is no room for prejudice.
The Bible tells us how good and pleasant it is when God’s people live together in unity. We must speak our minds openly, debate our disagreement honestly but always pursue solidarity. When America is united, America is totally unstoppable.
There should be no fear. We are protected, and we will always be protected. And most importantly, We will be protected by the great men and women of our military and law enforcement. We will be protected by God.
Finally, we must think big and dream even bigger. In America, we understand that a nation is only living as long as it is striving. We will no longer accept politicians who are all talk and no action, constantly complaining but never doing anything about it.
The time for empty talk is over. Now arrives the hour of action.
Do not allow anyone to tell you that it cannot be done. No challenge can match the heart and fight and spirit of America. We will not fail. Our country will thrive and prosper again. We stand at the birth of a new millennium, ready to unlock the mysteries of space, to free the earth from the miseries of disease and to harness the energies, industries and technologies of tomorrow. A new national pride will stir ourselves, lift our sights and heal our divisions. It’s time to remember that old wisdom our soldiers will never forget – that whether we are black or brown or white, we all bleed the same red blood of patriots.
We all enjoyed the same glorious freedoms, and we all salute the same great American flag.
And whether a child is born in the urban sprawl of Detroit or the windswept plains of Nebraska, They look up at the same night sky, they build a heart with the same dreams and they are infused with the breath of life by the same Almighty Creator.
So to all Americans in every city near and far, small and large, from mountain to mountain, from ocean to ocean, hear these words – you will never be ignored again.
Your voice, your hopes and your dreams will define our American destiny. Together, And your courage and goodness and love will forever guide us along the way. We will make America strong again. We will make America wealthy again. We will make America proud again. We will make America safe again. And yes, together, thank you. we will make America great again. God bless you. And God bless America. Thank You.
draft2.txt
Thank you. Thank you very much, everyone. Sorry to keep you waiting. Complicated business, complicated. Thank you very much.
I’ve just received a call from Secretary Clinton. She congratulated us. It’s about us. On our victory, and I congratulated her and her family on a very, very hard-fought campaign.
I mean she fought very hard. Hillary has worked very long and very hard over a long period of time, and we owe her a major debt of gratitude for her service to our country.
I mean that very sincerely. Now it is time for America to bind the wounds of pision, have to get together, to all Republicans and Democrats and independents across this nation I say it is time for us to come together as one united people.
It is time. I pledge to every citizen of our land that I will be president for all of Americans, and this is so important to me. For those who have chosen not to support me in the past, of which there were a few people, I’m reaching out to you for your guidance and your help so that we can work together and unify our great country. As I’ve said from the beginning, ours was not a campaign but rather an incredible and great movement, made up of millions of hard-working men and women who love their country and want a better, brighter future for themselves and for their family.
It is a movement comprised of Americans from all races, religions, backgrounds and beliefs, who want and expect our government to serve the people, and serve the people it will.
Working together we will begin the urgent task of rebuilding our nation and renewing the American dream. I’ve spent my entire life in business, looking at the untapped potential in projects and in people all over the world.
That is now what I want to do for our country. Tremendous potential. I’ve gotten to know our country so well. Tremendous potential. It is going to be a beautiful thing. Every single American will have the opportunity to realize his or her fullest potential. The forgotten men and women of our country will be forgotten no longer.
We are going to fix our inner cities and rebuild our highways, bridges, tunnels, airports, schools, hospitals. We’re going to rebuild our infrastructure, which will become, by the way, second to none, and we will put millions of our people to work
as we rebuild it. We will also finally take care of our great veterans who have been so loyal, and I’ve gotten to know so many over this 18-month journey.
The time I’ve spent with them during this campaign has been among my greatest honors.
Our veterans are incredible people. We will embark upon a project of national growth and renewal. I will harness the creative talents of our people and we will call upon the best and brightest to leverage their tremendous talent for the benefit of all. It is going to happen. We have a great economic plan. We will double our growth and have the pest economy anywhere in the world. At the same time we will get along with all other nations, willing to get along with us. We will be. We will have great relationships. We expect to have great, great relationships. No dream is too big, no challenge is too great. Nothing we want for our future is beyond our reach.
America will no longer settle for anything less than the best. We must reclaim our country’s destiny and dream big and bold and daring. We have to do that. We’re going to dream of things for our country, and beautiful things and successful things once again.
I want to tell the world community that while we will always put America’s interests first, we will deal fairly with everyone, with everyone.
All people and all other nations. We will seek common ground, not hostility, partnership, not conflict. And now I would like to take this moment to thank some of the people who really helped me with this, what they are calling tonight a very, very historic victory.
First I want to thank my parents, who I know are looking down on me right now. Great people. I’ve learned so much from them. They were wonderful in every regard. I are truly great parents. I also want to thank my sisters, Marianne and Elizabeth who are here with us tonight. Where are they They’re here someplace. They’re very shy actually.
And my brother Robert, my great friend. Where is Robert Where is Robert My brother Robert, and they should be on this stage but that’s okay. They’re great.
And also my late brother Fred, great guy. Fantastic guy. Fantastic family. I was very lucky.
Great brothers, sisters, great, unbelievable parents. To Melania and Don and Ivanka and Eric and Tiffany and Barron, I love you and I thank you, and especially for putting up with all of those hours. This was tough.
This was tough. This political stuff is nasty and it is tough. So I want to thank my family very much. Really fantastic. Thank you all. Thank you all. Lara,
unbelievable job. Unbelievable. Vanessa, thank you. Thank you very much. What a great group.
You’ve all given me such incredible support, and I will tell you that we have a large group of people. You know, they kept saying we have a small staff. Not so small. Look at all of the people that we have. Look at all of these people.
And Kellyanne and Chris and Rudy and Steve and David. We have got tremendously talented people up here, and I want to tell you it’s been very, very special.
I want to give a very special thanks to our former mayor, Rudy Giuliani. He’s unbelievable. Unbelievable. He traveled with us and he went through meetings, and Rudy never changes. Where is Rudy. Where is he
[Chanting “Rudy”]
Gov. Chris Christie, folks, was unbelievable. Thank you, Chris. The first man, first senator, first major, major politician — let me tell you, he is highly respected in Washington because he is as smart as you get, senator Jeff sessions. Where is Jeff A great man. Another great man, very tough competitor. He was not easy. He was not easy. Who is that Is that the mayor that showed up Is that Rudy
Up here. Really a friend to me, but I’ll tell you, I got to know him as a competitor because he was one of the folks that was negotiating to go against those Democrats, Dr. Ben Carson. Where’s been Where is Ben By the way, Mike Huckabee is here someplace, and he is fantastic. Mike and his familiar bring Sarah, thank you very much. Gen. Mike Flynn. Where is Mike And Gen. Kellogg. We have over 200 generals and admirals that have endorsed our campaign and there are special people. We have 22 congressional medal of honor people. A very special person who, believe me, I read reports that I wasn’t getting along with him. I never had a bad second with him. He’s an unbelievable star. He is – that’s right, how did you possibly guess Let me tell you about Reince. I’ve said Reince. I know it. I know it. Look at all of those people over there. I know it, Reince is a superstar. I said, they can’t call you a superstar, Reince, unless we win it. Like secretariat. He would not have that bust at the track at Belmont.
Reince is really a star and he is the hardest working guy and in a certain way I did this. Reince, come up here. Get over here, Reince.
Boy, oh, boy, oh, boy. It’s about time you did this right. My god. Nah, come here. Say something.
Amazing guy. Our partnership with the RNC was so important to the success and what we’ve done, so I also have to say, I’ve gotten to know some incredible people.
The Secret Service people. They’re tough and they’re smart and they’re sharp and I don’t want to mess around with them, I can tell ya. And when I want to go and wave to a big group of people and they rip me down and put me back down in the seat, but they are fantastic people so I want to thank the Secret Service.
And law enforcement in New York City, they’re here tonight. These are spectacular people, sometimes underappreciated unfortunately, we we appreciate them. So it’s been what they call an historic event, but to be really historic, we have to do a great job and I promise you that I will not let you down. We will do a great job. We will do a great job. I look very much forward to being your president and hopefully at the end of two years or three years or four years or maybe even eight years you will say so many of you worked so hard for us, with you you will say that — you will say that that was something that you were — really were very proud to do and I can — thank you very much.
And I can only say that while the campaign is over, our work on this movement is now really just beginning. We’re going to get to work immediately for the American people and we’re going to be doing a job that hopefully you will be so proud of your president. You will be so proud. Again, it’s my honor.
It’s an amazing evening. It’s been an amazing two-year period and I love this country. Thank you.
一个查询演讲稿的网址:
https://www.haowenwang.com/