常用Python技巧与知识

‘1  2     3'.split()=>['1','2','3']

'1  2     3'.split(None,1)=>['1','2    3']

'1,,2'.split(',')=>['1',''.'2']


我们把可能发生错误的语句放在try模块里,用except来处理异常。except可以处理一个专门的异常,也可以处理一组圆括号中的异常,如果except后没有指定异常,则默认处理所有的异常。每一个try,都必须至少有一个except

try:

pass

except(IOError ,ZeroDivisionError),e


Lambda Expression:

Small anonymous functions can be created with thelambdakeyword. This function returns the sum of its two arguments:lambdaa,b:a+b.Lambdafunctions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:

代码

book_list=sorted(book_list,key=lambda x:x[1],reverse=True )


str.join(iterable)

Return a string which is the concatenation of the strings in theiterableiterable. The separator between elements is the string providing this method.

a='/'.join(['a','b','c'])=>'a/b/c'


Python的字典排序:

```

a={'2':10,'3':30,'4':3}

sorted(a.items(),key=lambda x:x[1],reverse=False)

```


```

>>> a=[(1,2),('3','a')]

>>> {x:y for x,y in a}

{'3': 'a', 1: 2}

```

你可能感兴趣的:(常用Python技巧与知识)