码迷,mamicode.com
首页 > 其他好文 > 详细

笨办法32循环和列表

时间:2017-12-23 11:56:04      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:div   not   number   sts   tar   first   技术分享   append   and   

代码如下:

 1 fruits = [apples, oranges, pears, apricots]
 2 change = [1, pennies, 2, dimes, 3, quarters]
 3 
 4 # this first kind of for-loop goes through a list
 5 for number in the_count:
 6     print "This is count %d" % number
 7 
 8 # same as above
 9 for fruit in fruits:
10     print "A fruit of type: %s" % fruit
11 
12 # also we can go through mixed lists too
13 # notice we have to use %r since we don‘t know what‘s in it
14 for i in change:
15     print "I got %r" % i
16 
17 # we can also build lists, first start with an empty one
18 elements = []
19 
20 # then use the range function to do 0 to 5 counts
21 for i in range(0, 6):
22     print "Adding %d to the list." % i
23     # append is a function that lists understand
24     elements.append(i)
25 
26 # now we can print them out too
27 for i in elements:
28     print "Element was: %d" % i

运行结果:

技术分享图片

相关内容:

1.append 
用于在列表末尾追加新的对象:
>>> lst = [1, 2, 3] >>> lst.append(4) >>> lst [1, 2, 3, 4]

2.count
统计某个元素在列表中出现的次数:
>>> [‘to‘,‘be‘,‘or‘,‘not‘,‘to‘,‘be‘].count(‘to‘)
2
>>> x =[[1,2],1,1,[2,1,[1,2]]]
>>> x.count(1)
2
>>> x.count([1,2])
1

3.extend
在列表的末尾一次性追加另一个序列中的多个值

 

笨办法32循环和列表

标签:div   not   number   sts   tar   first   技术分享   append   and   

原文地址:http://www.cnblogs.com/p36606jp/p/8088389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!