笨办法学Python第39节
之前用的第三版的书,昨天发现内容不对,八块腹肌又给我下了第四版,这次的内容才对上。本节的代码如下:
ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that" stuff = ten_things.split(' ') more_stuff = ["Day","Night","Song", "Frisbee","Corn","Bananan","Girl","Boy"] while len(stuff)!=10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "There's %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])
运行结果如下:
列表的操作中几点要注意:
stuff = ten_things.split(' '):以空格为标示分割字符串ten_things。
print stuff[1]:输出列表中序号是1的元素,在这里是Oranges。
print stuff[-1]:输出列表中最后一个元素。
print stuff.pop():输出列表中最后一个元素并在返回的时候删除。
print ' '.join(stuff):将列表中的元素用空格连接起来。
print '#'.join(stuff[3:5]):将序号为3的元素和序号为4的元素用#连接起来,注意不包括序号为5的元素。