python 学习笔记3

xiaoxiao2021-02-27  254

python learning notes

Some senior attributes

1.Slice

cut a piece of elements from the whole container. sytnax:object[beginIndex endIndex (every x)] this provides us an easy way to get fragment of object.

2.iterate

iterate both value and key: for key,value in container.items() iterate only value: for value in container.values()

one more thing to mention: how do we get index in for loop? python provides us enumerate to get index of each element:

for i,key in enumerate([1,2],[2,3],[42,42]): print(i,key)

3.list comprehensions

It can produce list using a line of code. e.g.

[d*d for d in range(10) if d%2==0]

in the above statement, we get a list in which its elements are 4,36,..,100(n^2,&& n is even number).

4.generator

Python provided us a new tool that doesn’t appear in c/c++. That’s generator. Generator allow us to calculate the element when we actually need this element. The generator saves algorithm to produce the element. e.g. (x*x for x in range(10)). You can find that the difference between generator and list comprehension is that generator just uses parenthesis in place of a pair of bracket. Often we use for loop to traverse the whole container. But this tool seems one-off. When we want to use it in function, just use yield to tell compiler this is a generator.

转载请注明原文地址: https://www.6miu.com/read-10154.html

最新回复(0)