码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-07-05 20:31:34      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

新手在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

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

标签:

原文地址:http://www.cnblogs.com/Attenton/p/5644672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!