Exercise 1: Write a function called chop
that takes a list and modifies it, removing the first and last elements, and returns None
. Then write a function called middle
that takes a list and returns a new list that contains all but the first and last elements.
1.def chop():
numlist = list()
count = 0
while True:
value = input('please enter the number')
if value == 'done':break
value = float(value)
numlist.append(value)
count = count + 1
numlist = numlist[1:count-1]
print(numlist)
chop()
2.def middle():
numlist = list()
count = 0
while True:
value = input('please enter the number')
if value == 'done':break
value = float(value)
numlist.append(value)
count = count + 1
newlist = numlist[1:count-1]
print(newlist)
middle()
运行结果:
please enter the number 1 please enter the number 2 please enter the number 3 please enter the number 4 please enter the number done
[2.0, 3.0]
Exercise 3: Rewrite the guardian code in the below example without two if
statements. Instead, use a compound logical expression using the or
logical operator with a single if
statement.
example:
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
# print('Debug:', words)
if len(words) == 0 : continue
if words[0] != 'From' : continue
print(words[2])
fname = input('enter the file name')
fhand = open(fname)
for s in fhand:
t = s.split()
if len(t) == 0 or t[0] != 'From': continue
print(t[2])
Exercise 4: Find all unique words in a file
Shakespeare used over 20,000 words in his works. But how would you determine that? How would you produce the list of all the words that Shakespeare used? Would you download all his work, read it and track all unique words by hand?
Let’s use Python to achieve that instead. List all unique words, sorted in alphabetical order, that are stored in a file romeo.txt
containing a subset of Shakespeare’s work.
To get started, download a copy of the file www.py4e.com/code3/romeo.txt. Create a list of unique words, which will contain the final result. Write a program to open the file romeo.txt
and read it line by line. For each line, split the line into a list of words using the split
function. For each word, check to see if the word is already in the list of unique words. If the word is not in the list of unique words, add it to the list. When the program completes, sort and print the list of unique words in alphabetical order.
file = open('romeo.txt')
unilist = list()
for line in file:
wordlist = line.split()
for word in wordlist:
if word in unilist:
continue
else: unilist.append(word)
unilist.sort()
print(unilist)
运行结果:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
个人练习记录,欢迎一起讨论~
如需转载请联系作者并注明出处。