例子1
a=4
b=a
print a,b
print id(a)
print id(b)
b=5
print a,b
print id(a)
print id(b)
动行结果如下:
4 4
23236880
23236880
4 5
23236880
23236856
解释:
当a=4,b=a时,存放4这个值与内存地址 ,与a,b两个变量名绑定了,所以 id(a),id(b)得到的是同一个值,都是存放4的内存地址
当b=5时,这时b与原先存放4的内在地址解绑了,然后与存放5的内存地址绑定在了一起,所以 id(b)打印的是存放5的内存地址
这种机制可以节约内存
例子2:
a="hello"
print (id(a))
a=3
print (id(a))
结果:
140026927010880
13029672
解释:
当a="hello"时,a与内在地址140026927010880 绑定了,当a=3时,a与内存地址13029672绑定了,还有一点非常 重要的是,由于内存地址 140026927010880后面 没有与任何变量名绑定,所以 python的解释器会自动收回这一部分内存地址
基本数据类型中需要注意的地方
a=3
print type(a) #a为整型
a=3L
print type(a) #a为长整型
a=2.3
print type(a) #float
a=2.3e10
print type(a) #float
a="2.3e10"
print type(a) #string
a="3.12e-1"
print a,type(a) # "3.12e-1 <type "str">
a=float(a)
print a,type(a) #0.312 <type "float">
a=3.12e10
print type(a) #<type "flaot">
a=4+3j
print a,type(a)
(4+3j) <type 'complex'>
产生随机数的方法:
import random
ra=random.randint(1,10)
print ra
使用PyQt4.QtCore 包含对象和函数的 方法
from PyQt4.QtCore import *
x = QString()
y = QDate()
请和上面的使用方式进行对比
import PyQt4
x = PyQt4.QtCore.QString()
y = PyQt4.QtCore.QDate()
chr(int)
print chr(97) #返回 字符'a',数据类型为str
unichr(int)
print unichr(8364) #返回unicode字符,数据类型为str
ord(char)
print ord('a') #打印出 97,打印出字符对应的 数字编码值
关于子字符串
a="hello world"
a[:3] #前3个字符
a[-3:] #最后3个字符
a[5:7] #5,6
字符串或字符的查找,找不到匹配字符时,返回 -1 (也可使用a.index("is"))
a="hello today is a good day"
print a.find("is")
print a[a.find("is")]
12
i
英文句子首字母大字,title()函数
a.title()
字符串的格式化输出
stra="hello %s,%d,%i,%f" %("baby",33,44,44.4)
print stra #hello baby,44.400000
子字符串a,是否在字符串s中存在
if a in s:
if a not in s:
字符串的拼接
a+s
字符重的多次重复
a="234"
a*3
len(s)
s.count("ab")
s="hello ll ll ab ll"
print s.count('ll') #打印 4
s.endswith(x)
s.startxwith(x)
s.find(x)
s.rfind(x) #从右边开始找
s.isdigit() #是否 全为数字
s.isalpha() #是否 全为字母
s.title()
s.lower()
s.upper()
s="who is on duty today"
print s,s.replace("who is","I am") #who is on duty today I am on duty today #注意 ,不会改变原来的s字符串
s.strip() #去掉首尾的whitespace
In [14]: a=("helo") #还是str类型
In [15]: type(a)
Out[15]: str
In [16]: a=("helo",) #tuple类型
In [17]: type(a)
Out[17]: tuple
In [18]: a="ell","dsf",4,4 #这种也是tuple类型
In [19]: type(a)
Out[19]: tuple
tuple,list,dict这三类容器都是可以嵌套的
x in List
x not in list
L +m
下面是list扩展的方法
In [20]: a=[1,2,3]
In [21]: b=[4,5,6]
In [22]: a+b
Out[22]: [1,3,6]
In [23]: a.extend(b)
In [24]: a
Out[24]: [1,6] #可以看到a发生了改变
In [28]: a=[1,1,5]
In [29]: a.count(1) #统计a中 元素 1的个数
Out[29]: 4
list.index(x)
list.append(x)
list.extend(m)
list.insert(i,x) #position i
l.remove (x) #最左边遇到的x
list.pop() #将list最右边的元素作为返回值弹出 Returns and removes the rightmost item of list L
L.pop(i) #Returns and removes the item at index position int i in L
In [31]: a
Out[31]: [1,4]
In [32]: a.reverse()
In [33]: a
Out[33]: [4,1]
list.sort()
关于list的 shadow copy
seaweed = ["Aonori","Carola","Dulse"]
macroalgae = seaweed
print seaweed,macroalgae
macroalgae[2] = "Hijiki"
print seaweed,macroalgae
下面是输出结果,可以看到改变macroalgae时,seaweed也发生了改变,这是由于python默认使用的shadow copy,可以认为对于list,macroalgae 为seaweed的别名
['Aonori','Carola','Dulse'] ['Aonori','Dulse']
['Aonori','Hijiki'] ['Aonori','Hijiki']
如果重新复制一个完全一新的list出来,如下操作
b=[1,2334,35534]
a=b[:]
如上,这样改变a中的元素时,也不影响b,此时a对象使用的内存空间完全不同于b
创建dict变量更直观的方法
d=dict(a=3,b=4,c=5,e="hello")
print d
{'a': 3,'c': 5,'b': 4,'e': 'hello'}
在ipython中,使用dir函数,查看一个module中,有哪些class,method,funciton,property
#dir函数是非常有用的
In [53]: import PyQt4
In [54]: dir(PyQt4)
Out[54]:
['QtCore','builtins','doc','file','name','package','path']
In [55]: dir(PyQt4.QtCore)
Out[55]:
['PYQT_CONFIGURATION','PYQT_VERSION','PYQT_VERSION_STR','QAbstractAnimation','QAbstractEventDispatcher','QAbstractFileEngine','QAbstractFileEngineHandler','QAbstractFileEngineIterator','QAbstractItemModel','QAbstractListModel','QAbstractState','QAbstractTableModel','QAbstractTransition','QAnimationGroup','QBasicTimer','QBitArray','QBuffer','QByteArray','QByteArrayMatcher','QChar','QChildEvent','QCoreApplication','QCryptographicHash','QDataStream','QDate','QDateTime','QDir','QDirIterator','QDynamicPropertyChangeEvent','QEasingCurve','QElapsedTimer','QEvent','QEventLoop','QEventTransition','QFSFileEngine','QFile','QFileInfo','QFileSystemWatcher','QFinalState','QGenericArgument','QGenericReturnArgument','QHistoryState','QIODevice','QLatin1Char','QLatin1String','QLibrary','QLibraryInfo','QLine','QLineF','QLocale','QMargins','QMetaClassInfo','QMetaEnum','QMetaMethod','QMetaObject','QMetaProperty','QMetaType','QMimeData','QModelIndex','QMutex','QMutexLocker','QObject','QObjectCleanupHandler','QParallelAnimationGroup','QPauseAnimation','QPersistentModelIndex','QPluginLoader','QPoint','QPointF','QProcess','QProcessEnvironment','QPropertyAnimation','QReadLocker','QReadWriteLock','QRect','QRectF','QRegExp','QResource','QRunnable','QSemaphore','QSequentialAnimationGroup','QSettings','QSharedMemory','QSignalMapper','QSignalTransition','QSize','QSizeF','QSocketNotifier','QState','QStateMachine','QString','QStringList','QStringMatcher','QStringRef','QSysInfo','QSystemLocale','QSystemSemaphore','QT_TRANSLATE_NOOP','QT_TR_NOOP','QT_TR_NOOP_UTF8','QT_VERSION','QT_VERSION_STR','QTemporaryFile','QTextBoundaryFinder','QTextCodec','QTextDecoder','QTextEncoder','QTextStream','QTextStreamManipulator','QThread','QThreadPool','QTime','QTimeLine','QTimer','QTimerEvent','QTranslator','QUrl','QUuid','QVariant','QVariantAnimation','QWaitCondition','QWriteLocker','QXmlStreamAttribute','QXmlStreamAttributes','QXmlStreamEntityDeclaration','QXmlStreamEntityResolver','QXmlStreamNamespaceDeclaration','QXmlStreamNotationDeclaration','QXmlStreamReader','QXmlStreamWriter','Q_ARG','Q_CLASSINFO','Q_ENUMS','Q_FLAGS','Q_RETURN_ARG','Qt','QtCriticalMsg','QtDebugMsg','QtFatalMsg','QtMsgType','QtSystemMsg','QtWarningMsg','SIGNAL','SLOT','license','bin','bom','center','dec','endl','fixed','flush','forcepoint','forcesign','hex','left','lowercasebase','lowercasedigits','noforcepoint','noforcesign','noshowbase','oct','pyqtBoundSignal','pyqtPickleProtocol','pyqtProperty','pyqtRemoveInputHook','pyqtRestoreInputHook','pyqtSetPickleProtocol','pyqtSignal','pyqtSignature','pyqtSlot','pyqtWrapperType','qAbs','qAddPostRoutine','qChecksum','qCompress','qCritical','qDebug','qErrnoWarning','qFatal','qFuzzyCompare','qInf','qInstallMsgHandler','qIsFinite','qIsInf','qIsNaN','qIsNull','qQNaN','qRegisterResourceData','qRemovePostRoutine','qRound','qRound64','qSNaN','qSetFieldWidth','qSetPadChar','qSetRealNumberPrecision','qSharedBuild','qSwap','qUncompress','qUnregisterResourceData','qVersion','qWarning','qrand','qsrand','reset','right','scientific','showbase','uppercasebase','uppercasedigits','ws']
python编程三本书:
Core PYTHON Programming
Python in a Nutshell by Alex Martelli
Python Cookbook 2nd Edition,