Python易忽视知识点小结


Posted in Python onMay 25, 2015

这里记录Python中容易被忽视的小问题

一、input(...)和raw_input(...)

#简单的差看帮助文档input(...)和raw_input(...)有如下区别 
>>> help(input) 
Help on built-in function input in module __builtin__: 
input(...) 
  input([prompt]) -> value 
  Equivalent to eval(raw_input(prompt)). 
>>> help(raw_input) 
Help on built-in function raw_input in module __builtin__: 
raw_input(...) 
  raw_input([prompt]) -> string 
    
  Read a string from standard input. The trailing newline is stripped. 
  If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. 
  On Unix, GNU readline is used if enabled. The prompt string, if given, 
  is printed without a trailing newline before reading. 
  
#可见 input会根据输入的内容eval结果来返回值,即输入纯数字,则得到的就是纯数字 
#     raw_input返回的才是字符串 
#test: 
>>> a = input("输入数字") 
输入数字1 
>>> type(a) 
<type 'int'> 
>>> b=raw_input("输入数字") 
输入数字1 
>>> type(b) 
<type 'str'>

ps:在python3.0以后的版本中,raw_input和input合体了,取消raw_input,并用input代替,所以现在的版本input接收的是字符串

二、python三目运算符

虽然Python没有C++的三目运算符(?:),但也有类似的替代方案,

那就是
1、 true_part if condition else false_part

>>> 1 if True else 0 
1 
>>> 1 if False else 0 
0 
>>> "True" if True else "False" 
'True' 
>>> "True" if True else "False" 
'Falser'

2、 (condition and   [true_part]   or   [false_part] )[0]

>>> (True and ["True"] or ["False"])[0] 
'True' 
>>> (False and ["True"] or ["False"])[0] 
'False' 
>>>

三、获得指定字符串在整个字符串中出现第N次的索引

# -*- coding: cp936 -*- 
def findStr(string, subStr, findCnt): 
  listStr = a.split(subStr,findCnt) 
  if len(listStr) <= findCnt: 
    return -1 
  return len(string)-len(listStr[-1])-len(subStr) 
#test 
a = "12345(1)254354(1)3534(1)14" 
sub = "(1)" 
N = 2   #查找第2次出现的位置 
print findStr(a,sub,N) 
N = 10   #查找第10次出现的位置 
print findStr(a,sub,N) 
#结果 
#>>>  
#14 
#-1

四、enumerate用法:

遍历序列的时候,可能同时需要用到序列的索引和对应的值,这时候可以采用enumerate方法进行遍历

enumerate的说明如下:

>>> help(enumerate) 
Help on class enumerate in module __builtin__: 
 
class enumerate(object) 
 | enumerate(iterable[, start]) -> iterator for index, value of iterable 
 |  
 | Return an enumerate object. iterable must be another object that supports 
 | iteration. The enumerate object yields pairs containing a count (from 
 | start, which defaults to zero) and a value yielded by the iterable argument. 
 | enumerate is useful for obtaining an indexed list: 
 |   (0, seq[0]), (1, seq[1]), (2, seq[2]), ... 
 |  
 | Methods defined here: 
 |  
 | __getattribute__(...) 
 |   x.__getattribute__('name') <==> x.name 
 |  
 | __iter__(...) 
 |   x.__iter__() <==> iter(x) 
 |  
 | next(...) 
 |   x.next() -> the next value, or raise StopIteration 
 |  
 | ----------------------------------------------------------------------
 | Data and other attributes defined here: 
 |  
 | __new__ = <built-in method __new__ of type object> 
 |   T.__new__(S, ...) -> a new object with type S, a subtype of T

五、遍历序列的方法

>>> List = ['a','b','c'] 
>>> for index, value in enumerate(List): 
  print index, value 
0 a 
1 b 
2 c 
>>>

六、使用python random模块的sample函数从列表中随机选择一组元素

import 
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
slice = random.sample(List, 5)
#从List中随机获取5个元素,作为一个片断返回  
print slice  
print List #原有序列并没有改变。

七、用json打印包含中文的列表字典等

# -*- coding:utf-8 -*- 
import json 
#你的列表 
listA = [{'path': ['[AWS] \xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xab Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 1080p x264 AAC][6E5CFE86].mp4'], 'length': 131248608L}, {'path': ['[AWS] \xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xab Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 720p x264 AAC][639D304A].mp4'], 'length': 103166306L}, {'path': ['[AWS] \xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xab Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 480p x264 AAC][5A81BACA].mp4'], 'length': 75198408L}]
#打印列表
print json.dumps(listA, encoding='UTF-8', ensure_ascii=False)

输出结果:

>>>  
[{"path": ["[AWS] 美少女战士 Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 1080p x264 AAC][6E5CFE86].mp4"], "length": 131248608}, {"path": ["[AWS] 美少女战士 Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 720p x264 AAC][639D304A].mp4"], "length": 103166306}, {"path": ["[AWS] 美少女战士 Sailor Moon Crystal - Moon Pride MV[BIG5][BDrip 480p x264 AAC][5A81BACA].mp4"], "length": 75198408}]

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python函数返回多个值的示例方法
Dec 04 Python
Python实现各种排序算法的代码示例总结
Dec 11 Python
Python OpenCV 直方图的计算与显示的方法示例
Feb 08 Python
python中subprocess批量执行linux命令
Apr 27 Python
Python爬虫爬取新浪微博内容示例【基于代理IP】
Aug 03 Python
用pycharm开发django项目示例代码
Oct 24 Python
python 将字符串完成特定的向右移动方法
Jun 11 Python
详解Python是如何实现issubclass的
Jul 24 Python
opencv 获取rtsp流媒体视频的实现方法
Aug 23 Python
Python list运算操作代码实例解析
Jan 20 Python
Python中私有属性的定义方式
Mar 05 Python
详解Python IO编程
Jul 24 Python
Python中类型关系和继承关系实例详解
May 25 #Python
pymssql数据库操作MSSQL2005实例分析
May 25 #Python
python动态参数用法实例分析
May 25 #Python
Python文件去除注释的方法
May 25 #Python
python提取页面内url列表的方法
May 25 #Python
python实现批量改文件名称的方法
May 25 #Python
python基于右递归解决八皇后问题的方法
May 25 #Python
You might like
PHP curl模拟浏览器采集阿里巴巴的实现代码
2011/04/20 PHP
PHP自定session保存路径及删除、注销与写入的方法
2014/11/18 PHP
yii的入口文件index.php中为什么会有这两句
2016/08/04 PHP
PHP 实现从数据库导出到.csv文件方法
2017/07/06 PHP
Thinkphp页面跳转设置跳转等待时间的操作
2019/10/16 PHP
jQuery下通过$.browser来判断浏览器.
2011/04/05 Javascript
jquery ajax学习笔记2 使用XMLHttpRequest对象的responseXML
2011/10/16 Javascript
javascript工具库代码
2012/03/29 Javascript
JS实现悬浮移动窗口(悬浮广告)的特效
2013/03/12 Javascript
js遍历、动态的添加数据的小例子
2013/06/22 Javascript
JS+flash实现chrome和ie浏览器下同时可以复制粘贴
2013/09/22 Javascript
自定义ExtJS控件之下拉树和下拉表格附源码
2013/10/15 Javascript
JS在Chrome浏览器中showModalDialog函数返回值为undefined的解决方法
2016/08/03 Javascript
微信小程序 小程序制作及动画(animation样式)详解
2017/01/06 Javascript
JavaScript 日期时间选择器一些小结
2018/04/02 Javascript
Vue 实现复制功能,不需要任何结构内容直接复制方式
2019/11/09 Javascript
小程序实现左滑删除的效果的实例代码
2020/10/19 Javascript
JS相册图片抖动放大展示效果的示例代码
2021/01/29 Javascript
python单元测试unittest实例详解
2015/05/11 Python
使用pandas的DataFrame的plot方法绘制图像的实例
2018/05/24 Python
Python学习小技巧总结
2018/06/10 Python
opencv3/C++ 平面对象识别&amp;透视变换方式
2019/12/11 Python
python suds访问webservice服务实现
2020/06/26 Python
使用python实现学生信息管理系统
2021/02/25 Python
Android interview questions
2016/12/25 面试题
保安员岗位职责
2013/11/17 职场文书
矫正人员思想汇报
2014/01/08 职场文书
工商管理专业大学生职业生涯规划范文
2014/03/09 职场文书
租房协议书范文
2014/08/20 职场文书
2015年秋季校长开学典礼致辞
2015/07/29 职场文书
电力企业职工培训心得体会
2016/01/11 职场文书
小数乘法教学反思
2016/02/22 职场文书
2019年教师入党申请书
2019/06/27 职场文书
MongoDB支持的数据类型
2022/04/11 MongoDB
GO语言异常处理分析 err接口及defer延迟
2022/04/14 Golang
java.util.NoSuchElementException原因及两种解决方法
2022/06/28 Java/Android