Python tips

Sequence:
Thus, shoplist[1:3] returns a slice of the sequence starting at position 1, includes position 2 but
stops at position 3 and therefore a slice of two items is returned. Similarly, shoplist[:] returns a
copy of the whole sequence.
You can also do slicing with negative positions. Negative numbers are used for positions from the end of
the sequence. For example, shoplist[:-1] will return a slice of the sequence which excludes the
last item of the sequence but contains everything else.

Reference:
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
mylist = shoplist[:] # make a copy by doing a full slice


Remember that an assignment statement for lists does not create a copy. You have to use slicing operation to make a copy of the sequence


Lambda function:

is a function that takes any number of arguments (including optional arguments)
and returns the value of a single expression. lambda functions can not contain commands, and they can not contain more than one expression. Don't try to squeeze too much into a lambda function; if you need something more complex, define a normal function instead and make it as long as you want.
lambda functions are a matter of style. Using them is never required; anywhere you could use them, you could define a separate normal function and use that instead. I use them in places where I want to encapsulate specific, non−reusable code without littering my code with a lot of little one−line functions


Receiving Tuples and Lists in Functions:

>>> def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
Due to the * prefix on the args variable, all extra arguments passed to the function are stored in args as a tuple. If a ** prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary

exec / eval statements:

The exec statement is used to execute Python statements which are stored in a string or file. For example, we can generate a string containing Python code at runtime and then execute these statements using the exec statement. A simple example is shown below.
>>> exec 'print "Hello World"'
Hello World


The eval statement is used to evaluate valid Python expressions which are stored in a string. A simple example is shown below.
>>> eval('2*3')
6





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值