第八章

习题8.1 编写chop函数,移除列表的头元素和尾元素,并返回None值;然后编写middle函数,移除列表的头元素和尾元素

def chop(phrase):
    length = len(phrase)
    phrase = phrase[1:length-1]
    #t = phrase[0]
    #m = phrase[length-1]
    #phrase.remove(t)
    #phrase.remove(m)
    
def middle(phrase):
    length = len(phrase)
    phrase = phrase[1:length-1]
    return phrase


words1 = ['a', 'b', 'c', 'd', 'e']
words2 = ['m', 'n', 'p', 'q', 's']
print 'chop is:', chop(words1)
print 'middle is:', middle(words2)


习题8.4 编写一个程序,打开romeo.txt文件,按行读取,对每一行使用split函数,将其分解成一系列的单词列表,对于每一个单词,检查它是否已经存在于列表之中,若单词未出现在列表中,把它添加进来

fname = raw_input('Please enter a file name: ')
try:
    fhand = open(fname)
except:
    print 'Please enter!'
    
count = 0  
empty = []
for line in fhand:
    words = line.split()
    if len(words) == 0:
        continue
    for word in words:
        i = 0
        if empty.__contains__(word):
            continue
        else:
            empty.append(word)
        
#   if len(empty) == 0:
#       empty.append(word)
#       count=0
#       for word2 in empty :
#          if empty[count] == word:
#              break
#          if count== (len(empty)-1) :
#              empty.append(word)
#          count=count+1


print  empty

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值