1、使用列表生成式生成如下列表:[1,9,25,49,81]
1 s = [i**2 for i in range(1,10)if i%2==1]2 print(s)
2、输入一个由英文单词组成的字符串(分隔符自定),将每个单词的长度计算出来并形成一个新列表,并统计所有单词的平均长度。
1 s = input("请输入一个由英文单词组成的字符串,空格作为分隔符").split() 2 num =len(s) 3 x =list() 4 for i in range(0,num): 5 x.append(len(s[i])) 6 average =sum(x)/len(x) 7 print(x) 8 print("平均单词长度%d",average)
3.输入一组数据,以逗号分隔,求出这组数据的平均值、最大值、最小值,并按从小到大顺序排序。
1 s = input("请输入一组数据,逗号作为分隔符").split(',') 2 num = len(s) 3 x = list() 4 for i in range(0,num): 5 x.append(int(s[i])) 6 average = sum(x)/len(x) 7 maxx = max(x) 8 minx = min(s) 9 list.sort(x)10 print("数据的平均值为",average)11 print("数据的最大值为",maxx)12 print("数据的最小值为",minx)13 print("数据从小到大排序为",x)
4.统计《哈姆雷特》中出现频率最高的几个词
1 #Calhamlet 2 def getText(): 3 txt = open("D:\hamlet.txt","r").read() 4 txt = txt.lower() 5 for ch in '!"#%@^&*():?/{}[]\\_+,.~`<>|"’': 6 txt = txt.replace(ch," ") 7 return txt 8 hamletTxt = getText() 9 words = hamletTxt.split()10 counts = {}11 for word in words :12 counts[word] = counts.get(word,0) +113 items = list(counts.items())14 items.sort(key=lambda x:x[1],reverse = True)15 for i in range(10):16 word,count = items[i]17 print("{0:<10}{1:>5}".format(word,count))18