Python易忽视知识点小结
这里记录Python中容易被忽视的小问题
一、input(...)和raw_input(...)
#简单的差看帮助文档input(...)和raw_input(...)有如下区别
>>>help(input)
Helponbuilt-infunctioninputinmodule__builtin__:
input(...)
input([prompt])->value
Equivalenttoeval(raw_input(prompt)).
>>>help(raw_input)
Helponbuilt-infunctionraw_inputinmodule__builtin__:
raw_input(...)
raw_input([prompt])->string
Readastringfromstandardinput.Thetrailingnewlineisstripped.
IftheuserhitsEOF(Unix:Ctl-D,Windows:Ctl-Z+Return),raiseEOFError.
OnUnix,GNUreadlineisusedifenabled.Thepromptstring,ifgiven,
isprintedwithoutatrailingnewlinebeforereading.
#可见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_partifconditionelsefalse_part
>>>1ifTrueelse0 1 >>>1ifFalseelse0 0 >>>"True"ifTrueelse"False" 'True' >>>"True"ifTrueelse"False" 'Falser'
2、(conditionand [true_part] or [false_part])[0]
>>>(Trueand["True"]or["False"])[0] 'True' >>>(Falseand["True"]or["False"])[0] 'False' >>>
三、获得指定字符串在整个字符串中出现第N次的索引
#-*-coding:cp936-*- deffindStr(string,subStr,findCnt): listStr=a.split(subStr,findCnt) iflen(listStr)<=findCnt: return-1 returnlen(string)-len(listStr[-1])-len(subStr) #test a="12345(1)254354(1)3534(1)14" sub="(1)" N=2#查找第2次出现的位置 printfindStr(a,sub,N) N=10#查找第10次出现的位置 printfindStr(a,sub,N) #结果 #>>> #14 #-1
四、enumerate用法:
遍历序列的时候,可能同时需要用到序列的索引和对应的值,这时候可以采用enumerate方法进行遍历
enumerate的说明如下:
>>>help(enumerate)
Helponclassenumerateinmodule__builtin__:
classenumerate(object)
|enumerate(iterable[,start])->iteratorforindex,valueofiterable
|
|Returnanenumerateobject.iterablemustbeanotherobjectthatsupports
|iteration.Theenumerateobjectyieldspairscontainingacount(from
|start,whichdefaultstozero)andavalueyieldedbytheiterableargument.
|enumerateisusefulforobtaininganindexedlist:
|(0,seq[0]),(1,seq[1]),(2,seq[2]),...
|
|Methodsdefinedhere:
|
|__getattribute__(...)
|x.__getattribute__('name')<==>x.name
|
|__iter__(...)
|x.__iter__()<==>iter(x)
|
|next(...)
|x.next()->thenextvalue,orraiseStopIteration
|
|----------------------------------------------------------------------
|Dataandotherattributesdefinedhere:
|
|__new__=<built-inmethod__new__oftypeobject>
|T.__new__(S,...)->anewobjectwithtypeS,asubtypeofT
五、遍历序列的方法
>>>List=['a','b','c'] >>>forindex,valueinenumerate(List): printindex,value 0a 1b 2c >>>
六、使用pythonrandom模块的sample函数从列表中随机选择一组元素
import List=[1,2,3,4,5,6,7,8,9,10] slice=random.sample(List,5) #从List中随机获取5个元素,作为一个片断返回 printslice printList#原有序列并没有改变。
七、用json打印包含中文的列表字典等
#-*-coding:utf-8-*-
importjson
#你的列表
listA=[{'path':['[AWS]\xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xabSailorMoonCrystal-MoonPrideMV[BIG5][BDrip1080px264AAC][6E5CFE86].mp4'],'length':131248608L},{'path':['[AWS]\xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xabSailorMoonCrystal-MoonPrideMV[BIG5][BDrip720px264AAC][639D304A].mp4'],'length':103166306L},{'path':['[AWS]\xe7\xbe\x8e\xe5\xb0\x91\xe5\xa5\xb3\xe6\x88\x98\xe5\xa3\xabSailorMoonCrystal-MoonPrideMV[BIG5][BDrip480px264AAC][5A81BACA].mp4'],'length':75198408L}]
#打印列表
printjson.dumps(listA,encoding='UTF-8',ensure_ascii=False)
输出结果:
>>>
[{"path":["[AWS]美少女战士SailorMoonCrystal-MoonPrideMV[BIG5][BDrip1080px264AAC][6E5CFE86].mp4"],"length":131248608},{"path":["[AWS]美少女战士SailorMoonCrystal-MoonPrideMV[BIG5][BDrip720px264AAC][639D304A].mp4"],"length":103166306},{"path":["[AWS]美少女战士SailorMoonCrystal-MoonPrideMV[BIG5][BDrip480px264AAC][5A81BACA].mp4"],"length":75198408}]
希望本文所述对大家的Python程序设计有所帮助。