您的位置:首页 > 编程语言 > Python开发

《笨办法学python》加分习题32——我的答案

2017-09-03 21:12 423 查看
这是我自己学习的答案,会尽力写的比较好。还望大家能够提出我的不足和错误,谢谢!

**

原文例题:

**

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number

# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)

# now we can print them out too
for i in elements:
print "Element was: %d" % i


例题中使用range()函数,通过pydoc得知:



原型:range(start, stop, step)

返回了一个列表,列表中的元素就是start, start + step, … ,stop-1(你们明白就好,不一定是这个数)

append()是list的一个方法,作用是将元素添加到list的最后面:



**

习题答案:

**

1、如上所述

2、试了一下,确实可以。反正range(0,6) 也是等于 [0, 1, 2, 3, 4, 5]也是个列表。

3、我直接拉图片吧:



都是字面的意思:

list方法名称作用
append()添加元素到list的尾巴去
count()括号内元素在list中出现的次数
extend()通过迭代来扩展list,应该就是迭代进list的内容,觉得就是append()+for循环。就是把别的list加到原来list的末尾
index()索引,找到括号内元素在List中在哪里第一次出现的
insert()在index元素前插入一个元素
pop()删除并且返回索引处的元素
remove()删除第一个出现的括号内的对象
reverse()颠倒list中的值
sort()排序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: