- 学习测试开发的Day81,真棒!
- 学习时间为1H30M
- 第八次全天课(上午视频2H05M-2H37M_end,下午视频0-10M)
练习7:找出句子中第二长的所有单词!
s="you do believe you Do Cboy old years a am I"
老师的
方法1代码
s="you do believe you Do Cboyu old years a am I"
word_list=s.split()
max_length=0
sec_max_length=0
for word in word_list:
if len(word)>max_length:
max_length=len(word)
elif len(word)<max_length and len(word)>sec_max_length:
sec_max_length=len(word)
print(sec_max_length)
for word in word_list:
if len(word)==sec_max_length:
print(word)
结果输出:
PS D:\0grory\day8> python .\t_second.py
5
Cboyu
years
PS D:\0grory\day8>
方法2代码
s="you do believe you Do Cboyu old years a am I"
word_list=s.split()
word_count_dict = {}#字母的长度作为key,value是个list
for word in word_list:
if len(word) in word_count_dict .keys():
word_count_dict[len(word)].append(word)
else:
word_count_dict[len(word)]=[word]
print(word_count_dict)
sec_max_length=sorted(word_count_dict)[-2]
for i in word_count_dict[sec_max_length]:
print(i)
输出:
PS D:\0grory\day8> python .\dict_second.py
{1: ['a', 'I'], 2: ['do', 'Do', 'am'], 3: ['you', 'you', 'old'], 5: ['Cboyu', 'years'], 7: ['believe']}
Cboyu
years
方法3代码
def L(word):
return len(word)
s="you do believe you Do Cboyu old years a am I"
word_list=s.split()
sorted_list=sorted(word_list,key=L)
print(sorted_list)
max_len=len(sorted_list[-1])
sec_len=0
for i in sorted_list[::-1]:
if len(i)<sec_len:
break
if len(i)!=max_len:
sec_len=len(i)
print(i)
输出
PS D:\0grory\day8> python .\f3_second.py
['a', 'I', 'do', 'Do', 'am', 'you', 'you', 'old', 'Cboyu', 'years', 'believe']
years
Cboyu
PS D:\0grory\day8>
练习8:统计以下一句话中,有几个开头为ab的单词
abandon your dream abnoram1 !
代码:
s="abandon your dream abnoram1 !"
s=s.split()
print(s)
for i in s:
if i[0]=='a' and i[1]=='b':
print(i)
结果:
PS D:\0grory\day8> python .\ab.py
['abandon', 'your', 'dream', 'abnoram1', '!']
abandon
abnoram1
PS D:\0grory\day8>
练习9:找到dream所在的字符串的坐标位置,返回开始和结束位置。
abandon your dream abnoram1 !
代码:
s="abandon your dream abnoram1 !"
s=list(s)
print(s)
l=len(s)
for i in range(l-4):
if s[i]=='d' and s[i+1]=='r' and s[i+2]=='e' and s[i+3]=='a' and s[i+4]=='m':
print(i,i+4)
输出
PS D:\0grory\day8> python .\dream.py
['a', 'b', 'a', 'n', 'd', 'o', 'n', ' ', 'y', 'o', 'u', 'r', ' ', 'd', 'r', 'e', 'a', 'm', ' ', 'a', 'b', 'n', 'o', 'r', 'a', 'm', '1', ' ', '!']
13 17
PS D:\0grory\day8>