本节学习下如何操作列表,注意几个函数的使用,append,pop,split,join,以及下标中索引的使用。
以下是ex38.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
ten_things = "AAA BBB CCC DDD EEE FFF GGG"
print "Wait there are not 10 things in that list. Let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There are %d items now." % len(stuff)
print "There we go: ", stuff
print "Let's do some things with stuff."
print stuff[1]
print stuff[-1]
print stuff.pop()
print ' '.join(stuff)
print '#'.join(stuff[3:5])
运行结果:
Wait there are not 10 things in that list. Let’s fix that.
Adding: HHHH
There are 8 items now.
Adding: GGGG
There are 9 items now.
Adding: FFFF
There are 10 items now.
There we go: [‘AAA’, ‘BBB’, ‘CCC’, ‘DDD’, ‘EEE’, ‘FFF’, ‘GGG’, ‘HHHH’, ‘GGGG’, ‘FFFF’]
Let’s do some things with stuff.
BBB
FFFF
FFFF
AAA BBB CCC DDD EEE FFF GGG HHHH GGGG
DDD#EEE