《笨办法学Python》 第39课手记

时间:2022-04-26
本文章向大家介绍《笨办法学Python》 第39课手记,主要内容包括《笨办法学Python》 第39课手记、本节课涉及的知识:、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

《笨办法学Python》 第39课手记

本节课讲列表的操作,用来做练习的代码中出现了之前用到过的几个函数,是一节复习课。你需要记住它们。

原代码如下:

ten_things = "Apples Orange 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", "Banana", "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] # whoa!! fancy
print stuff.pop()
print ' '.join(stuff) # what? cool!
print '#'.join(stuff[3:5]) # super stellar!

结果如下:

本节课涉及的知识:

1.stuff.split(’ ‘),以空格为标志分割字符串,默认全部分割,可以在括号里”后面指定参数以使解释器按规定次数分割。 2.stuff.append(next_one),向列表stuff中增添元素next_one,执行方式作者在文中有介绍。 3.print ‘#’.join(stuff[3:5]) ,用#将stuff中的第3个元素和第4个元素连接起来,[3:5]这个参数给出了要连接的元素在列表中的位置,注意不包括第5个元素。