提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目:
1.统计所输入字符串中单词的个数,单词之间用空格分隔。
代码:
print("请输入字符(以空格隔开):")
s=input().split()
print(len(s))
效果截图:
2.编写程序,删除一个list里面重复元素。
代码:
#实现删除一个list里面的重复元素
#s.append追加到列表尾部
def delList(L):
L1 = []
for i in L:
if i not in L1:
L1.append(i)
return L1
print("请输入列表list数据(空格隔开):")
#输入一个数组
arr = input()
list = [int(n) for n in arr.split()]
print("删除重复前:",list)
print("删除重复后:",delList(list))
效果截图:
3.编写程序,将列表[9,7,8,3,2,1,5,6]中的偶数变成它的平方,奇数保持不变。
代码:
list=[9,7,8,3,2,1,5,6]
for i in range(len(list)):
if(list[i]%2==0):
list[i]=list[i]**2
print(list)
效果截图:
4.编写程序,输入字符串,将其每个字符的ASCII码形成列表并输出。
代码:
str=input('请输入一个字符串:')
a=[0]*len(str) #数组初始化
i=0
for x in str:
a[i]=ord(x) #将字符转换为ASCII码
i=i+1
result=list(a)
print("字符串的ASCII码为:",result)
效果截图:
5.猜单词游戏,计算机随机产生一个单词,打乱字母顺序,供玩家猜测,采用控制字符界面。例如:
乱序后单词: luebjm
请你猜:jumble
真棒 ,你猜对了!
是否继续(Y/N):
…
代码:
import re
import random
#随意截取的段落
ch = ''' I like to be happy
Life is a colorful picture full of different feelings I'd like to be happy because happiness is important to everyone.
I have an unforgettable experience to share with you.
Last Sunday my parents gave me some pocket money and with the money I bought some books instead of snacks.
The next day I took the books to school. After lunch, I showed the books to my classmates and we read together.
We learned a lot from the interesting books. Both reading and sharing made me happy,
How I wish I were happy every day in rnv life!'''
#正则表达式匹配去掉【】内的字符
#re.sub的用法
#split()返回的是一个list
#set转为集合去重
word =re.sub("[\n.,!']" ,"",ch)
words = list(set(word.split()))
print("游戏开始")
isgo = 'y'
while(isgo=='y' or isgo=='Y'):
rword = random.choice(words)
cword = rword
jword = ""
while rword:
p = random.randrange(len(rword))
jword+=rword[p]
rword = rword[:p]+rword[(p+1):]
print("乱序后的单词:",jword)
print()
gword = input("请输入单词:")
while gword!=cword and gword!="":
print("猜错了,请继续")
gword = input("请再次输入单词")
if gword == cword:
print("真棒,你猜对了\n")
isgo = input("\n请问是否继续(Y/N) : ")
效果截图:
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了1.统计所输入字符串中单词的个数。2.删除一个list里面重复元素。3.将列表中的偶数变成它的平方,奇数保持不变。4.输入字符串,将其每个字符的ASCII码形成列表并输出.5.猜单词游戏的分析。