跟老齐学Python之关于循环的小伎俩

2019-10-05 16:57:19丽君

下面用zip()来试试:


>>> dict(zip(myinfor.values(),myinfor.keys()))
{'python': 'lang', 'qiwsir.github.io': 'site', 'qiwsir': 'name'}

呜呼,这是什么情况?原来这个zip()还能这样用。是的,本质上是这么回事情。如果将上面这一行分解开来,看官就明白其中的奥妙了。


>>> myinfor.values()    #得到两个list
['python', 'qiwsir', 'qiwsir.github.io']
>>> myinfor.keys()
['lang', 'name', 'site']
>>> temp = zip(myinfor.values(),myinfor.keys())     #压缩成一个list,每个元素是一个tuple
>>> temp
[('python', 'lang'), ('qiwsir', 'name'), ('qiwsir.github.io', 'site')]

>>> dict(temp)                          #这是函数dict()的功能,将上述列表转化为dictionary
{'python': 'lang', 'qiwsir.github.io': 'site', 'qiwsir': 'name'}

至此,是不是明白zip()和循环的关系了呢?有了它可以让某些循环简化。特别是在用python读取数据库的时候(比如mysql),zip()的作用更会显现。

enumerate

enumerate的详细解释,在《再深点,更懂list》中已经有解释,这里姑且复习。

如果要对一个列表,想得到其中每个元素的偏移量(就是那个脚标)和对应的元素,怎么办呢?可以这样:


>>> mylist = ["qiwsir",703,"python"]
>>> new_list = []
>>> for i in range(len(mylist)):
...     new_list.append((i,mylist[i]))
...
>>> new_list
[(0, 'qiwsir'), (1, 703), (2, 'python')]

enumerate的作用就是简化上述操作:


>>> enumerate(mylist)
<enumerate object at 0xb74a63c4>    #出现这个结果,用list就能显示内容.类似的会在后面课程出现,意味着可迭代。
>>> list(enumerate(mylist))
[(0, 'qiwsir'), (1, 703), (2, 'python')]

对enumerate()的深刻阐述,还得看这个官方文档:


class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
|
| Methods defined here:
|
| getattribute(...)
| x.getattribute('name') <==> x.name
|
| iter(...)
| x.iter() <==> iter(x)
|