python 学习笔记3

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值