您的位置:首页 > 其它

练习32:列表与for循环

2016-05-23 22:13 316 查看

本次练习代码

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'orange', '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 items
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


列表

列表是python中的一种数据结构,与C语言中的数组概念相似,都可以用来存储一组有关联的数据

比如:

#python
fruits = ['apple', 'pear', 'orange', 1, 2, 3]

//C语言
count[3] = {1,2,3};


可以看出,与C语言的数组相比,python的列表具有更大的灵活性与易用性(个人观点),主要体现在:

1,在python中可以直接在列表中存储字符串,而C语言中要使用数组存储字符串只能使用指针数组

2,python中的列表可以同时存储不同的数据类型的数据,而C语言中的数组只能存储单一类型

3,python的列表在声明时不用指定长度,可以根据实际需求添加删除数据,而C语言中的数组在声明时要求确定数组长度,多了容易造成数组空间的浪费,少了又可能会导致数组空间不足

当然,这也与两者侧重的方面有所不同相关,并不存在哪个语言更好的说法

tips: 在python中,可以使用append方法添加数据到列表结尾

具体格式:

list.append(<要添加的数据>)

还有一个extend方法,用来将一串列表数据添加至对象列表中

list.extend(<要添加的一串列表>)

*append()用法示例:
>>> mylist = [1,2,0,'abc']
>>> mylist
[1, 2, 0, 'abc']
>>> mylist.append(4)
>>> mylist
[1, 2, 0, 'abc', 4]
>>> mylist.append('haha')
>>> mylist
[1, 2, 0, 'abc', 4, 'haha']
>>>
**********************************************************************************************************************
extend()用法示例:
>>> mylist
[1, 2, 0, 'abc', 4, 'haha']
>>> mylist.extend(['lulu'])
>>> mylist
[1, 2, 0, 'abc', 4, 'haha', 'lulu']
>>> mylist.extend([aaa,'lalalala'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'aaa' is not defined
>>> mylist.extend(['123123','lalalala'])
>>> mylist
[1, 2, 0, 'abc', 4, 'haha', 'lulu', '123123', 'lalalala']
>>> mylist.extend([111111,222])
>>> mylist
[1, 2, 0, 'abc', 4, 'haha', 'lulu', '123123', 'lalalala', 111111, 222]
>>>
OVER!*


以上实例引用于 http://blog.sina.com.cn/s/blog_76e94d210100vxr9.html

for循环

个人觉得与其称for为循环语句,还不如称它为遍历语句更好理解点

格式:

for <变量> in <要遍历的数据(一般为列表或range函数生成的一组数)>:
循环代码


每次循环,for语句都会将<要遍历的数据(一般为列表或range函数生成的一组数)>里的下一个数据赋值给<变量>,直到<要遍历的数据(一般为列表或range函数生成的一组数)>遍历完成

例子:

for i in [1, 2, 3, 4, 5]
print i,

#输出为:1 2 3 4 5


tips: range()函数

range函数用于产生一个列表

格式:

range(1,5)
#产生1到5的列表(包含1,不包含5)
#产生的list == [1,2,3,4]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: