python教程---新手应该知道的几个小技巧

新手在coding时经常不了解一些技巧,从而代码会很长,很复杂,下面就将介绍几个新手应该知道的几个小技巧来简化代码。

1.反转字符串

>>> a =  "codementor"
>>> print "Reverse is",a[::-1]
Reverse is rotnemedoc

2.转置矩阵

>>> mat = [[1, 2, 3], [4, 5, 6]]
>>> zip(*mat)
[(1, 4), (2, 5), (3, 6)]

3.将列表数据重新分别存储在单独的变量中

>>> a = [1, 2, 3]
>>> x, y, z = a 
>>> x
1
>>> y
2
>>> z
3

4.将字符串列表合并为单独的一个新的字符串

>>> a = ["Code","mentor","Python","Developer"]                                                                         
>>> print " ".join(a)                                                                                 
Code mentor Python Developer  

5.一行代码swap两个变量

>>> a=7
>>> b=5
>>> b, a =a, b
>>> a
5
>>> b
7

6.不用循环打印 “codecodecodecode mentormentormentormentormentor”

>>> print "code"*4+' '+"mentor"*5
codecodecodecode mentormentormentormentormentor

7.将列表中的数组列表合并为一个整体

>>> import itertools 
>>>a = [[1, 2], [3, 4], [5, 6]]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]

8.讲只包含数字字符串转化为列表

>>> result = map(lambda x:int(x) ,raw_input().split())
1 2 3 4
>>> result
[1, 2, 3, 4]

 参考:https://www.codementor.io/python/tutorial/python-tricks-for-beginners

posted @ 2016-07-05 18:31  Attenton  阅读(142)  评论(0编辑  收藏  举报