- 实例: 下载一首英文的歌词或文章,将所有,.?!等替换为空格,将所有大写转换为小写,统计某几个单词出现的次数,分隔出一个一个的单词。
- 列表实例:由字符串创建一个作业评分列表,做增删改查询统计遍历操作。例如,查询第一个3分的下标,统计1分的同学有多少个,3分的同学有多少个等。
- 简要描述列表与元组的异同。
#1 实例: 下载一首英文的歌词或文章,将所有,.?!替换为空格,将所有大写转换为小写,统计某几个单词出现的次数,分隔出一个一个的单词。
str = '''
When you wake up in the morning
When you haven't started to think
There is a whole brand new day
Open wide and waiting for you
I know in life's sorrow
you're on the verge of drowning
May your tears flee with yesterday
blow away with the wind
When you wake up in the morning
When you haven't started to think
The world is out there calling
open eyes to new beginning
A newborn sun is shinning
Chasing shadows from your mind
Everything will be alive,
under the sunshine's smile
Come out from your corner
No doubt in join us
You can decide the future
Devote your youthful power to this world
Come together, hand in hand together
I know you'll do
We pray and believe
that tomorrow will be better.
No, I don't know what your name is
But you're so familiar to me
Cause we belong to one family
You can hear my heart calling
Life can be music,
rainbows can be reached
If you face yourself truly
keep striving for your dream
Come out from your corner
No doubt in join us
You can decide the future
Devote your youthful power to this world
Come together, hand in hand together
I know you'll do
We pray and believe
that tomorrow will be better.
When you wake up in the morning
When you haven't started to think
There is a whole brand new day
Open wide and waiting for you
I know in life's sorrow
you're on the verge of drowning
May your tears flee with yesterday
Blow away with the wind
Come out from your corner
No doubt in join us
You can decide the future
Devote your youthful power to this world
Come together, hand in hand together
I know you'll do
We pray and believe
that tomorrow will be better.
'''
# 将,?.!变成空格
str = str.replace(',',' ')
str = str.replace('
','')
# 将所有大写转换为小写
str = str.lower()
# 把歌词切片
words = str.split(' ')
# 统计tomorrow、will、be、better
print ('tomorrow:{0}'.format(str.count('tomorrow')))
print ('will:{0}'.format(str.count('will')))
print ('be:{0}'.format(str.count('be')))
print ('better:{0}'.format(str.count('better')))
#2. 由字符串创建一个作业评分列表增删改查统计遍历操作,全部改为数值 型,查询第一个3分的下标,1分的同学有多少个,3分有多少个
pi = '32132112332131'
list_pi = list(pi)
# 增加一个3分的
list_pi.append('3')
# 删除最后一个
list_pi.pop()
# 修改第二个
list_pi[1] = '2'
# 查询第三个
print(list_pi[2])
# 全部修改为数值型
for i in range(len(list_pi)):
list_pi[i] = int(list_pi[i])
#查询出第一个3分的下标
for i in range(len(list_pi)):
if list_pi[i] == 3:
print (i)
break
print ('1分的同学有{0}个'.format(list_pi.count(1)))
print ('3分的同学有{0}个'.format(list_pi.count(3)))
3.简要描述列表与元组的异同
答:元组和列表十分类似,只不过元组和字符串一样是不可变的即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。