python给初学者的一些技巧和知识

简介:

1 一行赋值序列和元组

1
2
3
4
5
6
In [ 11 ]: l  =  [ 'a' 'b' ]
In [ 12 ]: x,y  =  l
In [ 13 ]: x 
Out[ 13 ]:  'a'
In [ 14 ]: y
Out[ 14 ]:  'b'
1
2
3
4
5
6
In [ 15 ]: t  =  ( 1 , 2 )
In [ 16 ]: m,n  = t
In [ 17 ]: m
Out[ 17 ]:  1
In [ 18 ]: n
Out[ 18 ]:  2


2 交换变量

1
2
3
4
5
6
7
In [ 6 ]: m  =  3      
In [ 7 ]: n  =  4      
In [ 8 ]: m,n  =   n,m
In [ 9 ]: m
Out[ 9 ]:  4
In [ 10 ]: n
Out[ 10 ]:  3


3 语句在行内,if 的三目运算

1
2
In [ 19 ]:  print  'Hello'  if  True  else  'World'
Hello
1
2
3
4
5
6
7
In [ 20 ]: a  =  ' ni'  
In [ 21 ]: b  =   a.strip()  if  a.strip()  else  None
In [ 22 ]: b
Out[ 22 ]:  'ni'
In [ 23 ]: a  =  ' '  
In [ 24 ]: b  =   a.strip()  if  a.strip()  else  None
In [ 25 ]: b


4 连接--相同类型的数据可以连接拼接

1
2
3
4
In [ 27 ]: s  =  'my name is: '
In [ 28 ]: msg  =  +  'Andy'
In [ 29 ]: msg
Out[ 29 ]:  'my name is: Andy'
1
2
3
4
In [ 30 ]: l1  =  [ 'Apple' 'orange' ]
In [ 31 ]: l2  =  [ 'Banana' 'Grape' ]
In [ 32 ]: l1  +  l2
Out[ 32 ]: [ 'Apple' 'orange' 'Banana' 'Grape' ]


5 数字技巧

整数和浮点除

1
2
3
4
In [ 33 ]:  5  / 2
Out[ 33 ]:  2
In [ 34 ]:  5.0  / 2
Out[ 34 ]:  2.5

整数和浮点取余数

1
2
3
4
In [ 36 ]:  5  % 2
Out[ 36 ]:  1
In [ 37 ]:  5.00  % 2
Out[ 37 ]:  1.0


6 数字比较和少语言可以如此用法

1
2
3
4
In [ 43 ]:  if  x <  5  and  x > 2 :
    ....:      print  x
    ....:     
3

等于

1
2
3
4
In [ 44 ]:  if  2  < x <  5 :
    ....:      print  x
    ....:     
3


7 同时迭代两个列表(序列)

1
2
3
4
5
6
7
8
9
In [ 46 ]: l1
Out[ 46 ]: [ 'Apple' 'orange' ]
In [ 47 ]: l2
Out[ 47 ]: [ 'Banana' 'Grape' ]
In [ 48 ]:  for  item1, item2  in  zip (l1, l2):
    ....:      print  item1  +  ' vs '  +  item2
    ....:     
Apple vs Banana
orange vs Grape



8 带索引的列表迭代

1
2
3
4
5
In [ 51 ]:  for  index, item  in  enumerate (l1):
    ....:      print  index, item
    ....:     
0  Apple
1  orange
1
2
3
4
5
In [ 52 ]:  for  index, item  in  enumerate (l1):
    ....:      print  index  + 1 , item
    ....:     
1  Apple
2  orange



9 生成列表(列表推到式)

1
2
3
4
5
6
7
8
In [ 53 ]: numbers  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
In [ 54 ]: even  =  []
In [ 55 ]:  for  number  in  numbers:
    ....:      if  number % 2  = =  0 :
    ....:         even.append(number)
    ....:         
In [ 56 ]: even
Out[ 56 ]: [ 2 4 6 8 ]

等价于一行语句

1
2
3
In [ 59 ]: even  =  [ number  for  number  in  numbers  if  number  % 2  = =  0
In [ 60 ]: even
Out[ 60 ]: [ 2 4 6 8 ]


10 字典推导(只使用 python 2.7版本 不适合以下版本)

1
2
3
4
names  =  [ 'andy' 'jack' 'tom' 'john' ]
=  {key: value  for  value, key  in  enumerate (names)}
>>> d
{ 'john' 3 'andy' 0 'jack' 1 'tom' 2 }



11 列表转字符串

1
2
3
4
In [ 64 ]: l1
Out[ 64 ]: [ 'Apple' 'orange' ]
In [ 66 ]:  "," .join(l1)
Out[ 66 ]:  'Apple,orange'


12 字符串转列表

1
2
3
In [ 67 ]: ids  =  "4,57,9,22,31"
In [ 68 ]: ids.split( ',' )
Out[ 68 ]: [ '4' '57' '9' '22' '31' ]


13获取列表的子集(切片)

1
In [ 2 ]: x  =  [ 1 , 2 , 3 , 4 , 5 , 6 ]


获取前三个

1
2
In [ 3 ]: x[: 3 ]
Out[ 3 ]: [ 1 2 3 ]


获取index=0 到 index=4的

1
2
In [ 4 ]: x[ 1 : 5 ]
Out[ 4 ]: [ 2 3 4 5 ]


获取后面3个

1
2
In [ 5 ]: x[ - 3 :]
Out[ 5 ]: [ 4 5 6 ]

获取奇数(从第一个到最后一个,步长为2)

1
2
In [ 6 ]: x[:: 2 ]
Out[ 6 ]: [ 1 3 5 ]


获取偶数(从第一个到最后一个,步长为2)

1
2
In [ 7 ]: x[ 1 :: 2 ]
Out[ 7 ]: [ 2 4 6 ]


倒序

1
2
In [ 8 ]: x[:: - 1 ]
Out[ 8 ]: [ 6 5 4 3 2 1 ]


14 合并列表zip

n个列表通过zip函数后,返回一个n个元素组成的元组形式的列表(列表长度为最短的那个列表)

1
2
3
4
5
6
In [ 23 ]: l1
Out[ 23 ]: [ 1 2 3 4 ]
In [ 24 ]: l2
Out[ 24 ]: [ 6 7 8 9 ]
In [ 25 ]:  zip (l1,l2)
Out[ 25 ]: [( 1 6 ), ( 2 7 ), ( 3 8 ), ( 4 9 )]
1
2
In [ 17 ]: [x + for   x,y   in  zip (l1,l2)]
Out[ 17 ]: [ 7 9 11 13 ]


15 序列的映射map 

map(function, sequence[, sequence, ...]) -> list

多个序列通过function返回后返回一个新的列表,最好是序列的长度要一致(不一致的元素补None)

function 可以为None,那么map功能就和zip一样了

1
2
In [ 27 ]:  map ( None ,l1,l2)
Out[ 27 ]: [( 1 6 ), ( 2 7 ), ( 3 8 ), ( 4 9 )]
1
2
In [ 28 ]:  map ( lambda  x,y:x  + y , l1,l2)
Out[ 28 ]: [ 7 9 11 13 ]



16 插入一条常见知识,程序中出现中文执行程序报错

syntaxError: Non-ASCII character '\xe4' in file test.py on line 7


解决:

1
2
3
4
5
#!/usr/bin/env python
#encoding=utf-8
import  sys
reload (sys)
sys.setdefaultencoding( 'utf-8' )


以上格式肯定是不会出错,注意#encoding=utf-8 一定要在第二行,在其他行不起作用



17 可以定义一个python执行错误的函数,每次执行错误,调用即可

#python 参数输入错误的提示输入函数

1
2
3
4
def  exec_error(msg = None ):
     print  "\ 033 [ 1 ; 31 ; 40mUsage : python xxx.py { 0 | 1 | 2 | 3 | all }\ 033 [ 0m  \n\t \
     0 : None  level project,  1 :level  1  project,  2 :level  2  project,  3 :level  3  project,  all : all  project"
     sys.exit()


18 通过ip地址翻译的主机名的函数

#通过ip或者hostname解析获得hostname,ip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def  resolve_host(s):
     =  s.split( '.' )
     if  len (l) >  4 :
         return  "-"
     if  len (l)  = =  4 :
         ip  =  s
         try :
             hostname  =  socket.gethostbyaddr(s)[ 0 ]
         except  Exception,e:
             #print "could't look up name by ipaddress:",e
             #sys.exit(1)
             return  '-'
     else :
         return  '-'
     return  hostname



19 filter函数

python自带

常用过滤列表

用法:  filter(函数,列表)

递归传递列表的值到函数中函数返回值为true则作为新列表的元素

1
2
3
In [ 7 ]: l  =  [ 1 , 2 , 3 , 4 , 5 ]
In [ 8 ]:  filter ( lambda  x : x > 3 , l)
Out[ 8 ]: [ 4 5 ]


其实等价于 和生成序列的常用方法效果一样

1
[i  for  in  if  i >  3 ]


实践中的用途:

1
2
3
4
In [ 19 ]: task_id  = 4
In [ 20 ]: tasks  =  [{ "id" : 3 "title" : "three" }, { "id" : 4 "title" : "four" }, { "id" : 5 , "title" : "five" }]
In [ 21 ]:  filter ( lambda  i: i[ "id" = =  task_id ,tasks)
Out[ 21 ]: [{ 'id' 4 'title' 'four' }]


本文转自残剑博客51CTO博客,原文链接http://blog.51cto.com/cuidehua/1768413如需转载请自行联系原作者

cuizhiliang


相关文章
|
Python C# Java
Python知识梳理
这是个人学习笔记,非教程,内容会有些混乱 极简教程 数据类型 我们可以使用type()函数类获取对象的类型,Python3中内置数据类型包括:None,int,float,complex,str,list,dict,tuple,set,frozenset,range等,Python2中还有long类型,Python中并没有内置数组类型。
12631 0
|
Unix Python
笨办法学 Python · 续 第一部分:预备知识
第一部分:预备知识 原文:Part I: Initial Knowledge 译者:飞龙 协议:CC BY-NC-SA 4.0 自豪地采用谷歌翻译 你需要学习的第一件事就是一切事情。
1053 0
|
Python
Python知识总结帖
1、面向对象高级编程中----使用__slots__ 注意点:使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
526 0
|
C# 数据库 Python
python一些小知识
1、python连接mssql数据库编码问题   python一直对中文支持的不好,最近老遇到编码问题,而且几乎没有通用的方案来解决这个问题,但是对常见的方法都试过之后,发现还是可以解决的,下面总结了常用的支持中文的编码问题(这些方法中可能其中一个就能解决问题,也可能是多个组合)。
812 0
|
5天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
5天前
|
程序员 开发者 Python
Python网络编程基础(Socket编程) 错误处理和异常处理的最佳实践
【4月更文挑战第11天】在网络编程中,错误处理和异常管理不仅是为了程序的健壮性,也是为了提供清晰的用户反馈以及优雅的故障恢复。在前面的章节中,我们讨论了如何使用`try-except`语句来处理网络错误。现在,我们将深入探讨错误处理和异常处理的最佳实践。
|
9天前
|
缓存 监控 Python
解密Python中的装饰器:优雅而强大的编程利器
Python中的装饰器是一种强大而又优雅的编程工具,它能够在不改变原有代码结构的情况下,为函数或类添加新的功能和行为。本文将深入解析Python装饰器的原理、用法和实际应用,帮助读者更好地理解和利用这一技术,提升代码的可维护性和可扩展性。
|
26天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
154 0
|
19天前
|
程序员 C语言 Python
Python列表推导式:简洁与高效的编程利器
在Python编程中,列表推导式(List Comprehension)是一种强大且优雅的工具,它允许我们以简洁的方式创建新的列表。列表推导式在Python程序员中广受欢迎,因为它能够将复杂的循环和条件语句简化为一行代码,提高代码的可读性和执行效率。