for的基本操作
for是用来循环的,是从某个对象那里依次将元素读取出来。
>>> name_str = "hiekay"
>>> for i in name_str: #可以对str使用for循环
... print i,
...
h i e k a y
>>> name_list = list(name_str)
>>> name_list
['h', 'i', 'e', 'k', 'a', 'y']
>>> for i in name_list: #对list也能用
... print i,
...
h i e k a y
>>> name_set = set(name_str) #set还可以用
>>> name_set
set(['a', 'e', 'i', 'h', 'k', 'y'])
>>> for i in name_set:
... print i,
...
h i e k a y
>>> name_tuple = tuple(name_str)
>>> name_tuple
('h', 'i', 'e', 'k', 'a', 'y')
>>> for i in name_tuple: #tuple也能呀
... print i,
...
h i e k a y
>>> name_dict={"name":"hiekay","lang":"python","website":"hiekay.github.io"}
>>> for i in name_dict: #dict也不例外
... print i,"-->",name_dict[i]
...
lang --> python
website --> hiekay.github.io
name --> hiekay
for在list解析中,用途也不可小觑,这在讲解list解析的时候,也已说明,不过,还是再复习一下为好,所谓学而时常复习之,不亦哈哈乎。
>>> one = range(1,9)
>>> one
[1, 2, 3, 4, 5, 6, 7, 8]
>>> [ x for x in one if x%2==0 ]
[2, 4, 6, 8]
将上面所说的for循环,概括一下,就是下图所示:
用一个文字表述:
for iterating_var in sequence:
statements
iterating_var是对象sequence的迭代变量,也就是sequence必须是一个能够有某种序列的对象,特别注意没某种序列,就是说能够按照一定的脚标获取元素。当然,文件对象属于序列,我们没有用脚标去获取每行,如果把它读取出来,因为也是一个str,所以依然可以用脚标读取其内容。
zip
zip是什么东西?在交互模式下用help(zip),得到官方文档是:
zip(...) zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
通过实验来理解上面的文档:
>>> a = "hiekay"
>>> b = "github"
>>> zip(a,b)
[('h', 'g'), ('i', 'i'), ('e', 't'), ('k', 'h'), ('a', 'u'), ('y', 'b')]
>>> c = [1,2,3]
>>> d = [9,8,7,6]
>>> zip(c,d)
[(1, 9), (2, 8), (3, 7)]
>>> e = (1,2,3)
>>> f = (9,8)
>>> zip(e,f)
[(1, 9), (2, 8)]
>>> m = {"name","lang"}
>>> n = {"hiekay","python"}
>>> zip(m,n)
[('lang', 'python'), ('name', 'hiekay')]
>>> s = {"name":"hiekay"}
>>> t = {"lang":"python"}
>>> zip(s,t)
[('name', 'lang')]
zip是一个内置函数,它的参数必须是某种序列数据类型,如果是字典,那么键视为序列。然后将序列对应的元素依次组成元组,做为一个list的元素。
下面是比较特殊的情况,参数是一个序列数据的时候,生成的结果样子:
>>> a
'hiekay'
>>> c
[1, 2, 3]
>>> zip(c)
[(1,), (2,), (3,)]
>>> zip(a)
[('q',), ('i',), ('w',), ('s',), ('i',), ('r',)]
这个函数和for连用,就是实现了:
>>> c
[1, 2, 3]
>>> d
[9, 8, 7, 6]
>>> for x,y in zip(c,d): #实现一对一对地打印
... print x,y
...
1 9
2 8
3 7
>>> for x,y in zip(c,d): #把两个list中的对应量上下相加。
... print x+y
...
10
10
10
上面这个相加的功能,如果不用zip,还可以这么写:
>>> length = len(c) if len(c)<len(d) else len(d) #判断c,d的长度,将短的长度拿出来
>>> for i in range(length):
... print c[i]+d[i]
...
10
10
10
以上两种写法那个更好呢?还可以这么做呢:
>>> [ x+y for x,y in zip(c,d) ]
[10, 10, 10]
前面多次说了,list解析强悍呀。当然,还可以这样的:
>>> [ c[i]+d[i] for i in range(length) ]
[10, 10, 10]