python基础知识(一)

一、python的类型与操作

python的基础变量类型有如下:

     Number,         数字: 7

     String,         字符串: 'test'               -----------------------------------------------help(str)

     List,                列表: [1,2,3,4]         -----------------------------------------------help(list)

     Dictionaries,   字典: {'food': 'spam', 'taste': 'yum'}-----------------------------help(dict)

     Tuple,            元组:  (1,'spam',4,'U') ---------------------------------------------help(tuple)

     File                 文件: myfile = open('eggs','r') ----------------------------------help(file)

   其他的数据类型:Sets, types,None, Booleans

    查看某变量的类型:type(变量)

  

     (1) 数字类型

     数字类型,包括整数、长整数,浮点数,复数,其中复数由 real + imag(j/J)组成,如2+2j或2+2J。

>>> print 3.14*2
6.28
>>> import math
>>> print math.pi
3.14159265359
>>> import random
>>> print random.random()
0.600312398036
>>> print random.choice([1,2,3,4])
4
>>> 

   这里与数学相关的模块:math数学模块random随机模块

   简单运算符

     除 /          求余 %        位操作: 左移 << , 右移 >>, 按位或  |,按位与 &

     除 //         求幂 **    

     等于(==)和是(is)的概念

    “等于”是检查两个变量是不是相等。

    “是”是检查两个变量是不是引用同一个对象。  

>>> print 50.3/3 #除
16.7666666667
>>> print 50/3   #整数除
16
>>> print 50.0//3 #除后约去小数
16.0
>>> 8<<2          #左移2位
32
>>> 16>>2          #右移2位
4
>>> 
>>> 4|2            #按位或
6
>>> 8&0            #按位与
0
>>> 

   

   (2) 字符串类型(str)

  在python中,单引号'和双引号'',可以用来指示一个字符串,甚至在表示多行的时候,可以使用'三引号'',如,

>>> str1 = 'hello'
>>> str2 = "hello,world"
>>> str3 = '''
... my name is ahuang1900.
... the first
... the second
... the third,
... 
... ,,,
... 
... 
... ,,,
... 
... 
... 
... 
... 
... '''
>>> str3
'\nmy name is ahuang1900.\nthe first\nthe second\nthe third,\n\n,,,\n\n\n,,,\n\n\n\n\n\n'
>>> 


>>> #Chinese
... 
>>> #中文字符串
... 
>>> strCN='我爱python'
>>> print strCN
我爱python
>>> #len函数,测字符串长度
... 
>>> print len(strCN)
12
>>> print strCN[1] #访问第一个字符
�
>>> print strCN[-1] #访问最后一个字符
n
>>> strEN = 'spring comes and the flower is open...'
>>> print strEN
spring comes and the flower is open...
>>> print len(strEN)
38
>>> print strEN[0]
s
>>> print strEN[-1]
.
>>> print strEN[0:5] #for 0 to 4
sprin
>>> print strEN[0:-1]
spring comes and the flower is open..
>>> print strEN[0:] %从字符串开头,到字符串结尾
  File "<stdin>", line 1
    print strEN[0:] %从字符串开头,到字符串结尾
                     ^
SyntaxError: invalid syntax
>>> print strEN[0:] #从字符串开头,到字符串结尾
spring comes and the flower is open...
>>> print strEN[:-1]
spring comes and the flower is open..
>>> print strCN + strEN  #字符串可以进行+链接
我爱pythonspring comes and the flower is open...
>>> print strCN*2   #字符串进行乘法运算
我爱python我爱python
>>> 

这里的#是python的注释,%则是matlab的注释


   字符串方法:

    str1.find(var)            #查找字符串中子字符串最左端的索引(从0开始算),如果没有,则返回-1

>>> str1 = 'My name is ahuang1900'
>>> str1.find('is')
8
>>> str1.find('2')
-1
>>> str1[8]
'i'

    str1.find(var,n,m)     #n是起始点,m是结束点

>>> str1.find('is',1)
8
>>> str1.find('is',9)
-1
>>> str1.find('is',0,30)
8
 

    str1.joint  

    str1.lover()

    str1.replace()

    str1.split(str2)

    str1.strip()

    str1.translate() 


字符串方法----所有的方法都不能改变字符串的值

>>> strEN = 'I love python!'
>>> print strEN.find('love')
2
>>> print strEN.replace('love','~_~')
I ~_~ python!
>>> print strEN.split('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> print strEN.split(' ')
['I', 'love', 'python!']
>>> print strEN.upper() #转换为大写
I LOVE PYTHON!
>>> print strEN.isalpha()
False
>>> print strEN.rstrip()
I love python!
>>> 

获得帮助

>>> print dir(strEN) #取得帮助
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> 

>>> help(str)

多行字符串

>>> print """<div>
... <p>HTML Code goes here...</p>
... </div> """
<div>
<p>HTML Code goes here...</p>
</div> 
>>> 

注意事项:

    (1)字符串除了使用双引号""和单引号''表示外,还可以使用"""表示,如何需要表示换行或引号,则需要转义字符表示。如:\\表示\,\"表示"

    (2)在字符串前面加一个r表示raw string,即本字符串不转义。
    (3)如果要在字符串中存储Unicode的字符串,需要在字符串前面加上一个u,如uniStr = u'unicode 的字符串'
    (4)不能将字符串和数字相加(+)

    (5)函数ord将字符转换为ASCII码 $ print ord('d')     结果: 100
    (6)函数chr将ASCII码转换为字符 $ print chr(100)   结果: 'd'
    (7)格式化字符串
      print "%s -- %s -- %s"  % (42,3.1415, [ 1,2,3])   

    

   (3) 列表类型(list)

    列表的长度是动态的,可以任意添加和删除元素。

    列表(list),有点类似于C++中的vector,但是list中可以含不同类型的元素。

    列表按下标读取,当作数组处理,下标从0开始,-1表示最后一个元素。

    len函数可以计算列表的元素个数。

    创建连续的list:

    L=range(1,10)     #即创建L=[1,2,3,..,9],注意不含最后一个元素10.

    L=range(1,10,3)  #即创建L=[1,4,7],注意这里的每个元素间隔是3.

    list的方法:

    L.append(var)         #在列表中追加元素(push_back)

    L.insert(index,var)   #在列表的第index位置(从0开始),插入元素var.

    L.pop()                    #返回最后一个元素,并从list中删除

    L.pop(index)           #返回列表中的第index个元素,并从list中删除.

    L.remove(var)         #移除列表中的元素var

    L.count(var)            #统计列表中元素var出现的次数

    L.index(var)            #计算列表中元素var的索引号

    L.extend(L1)           #追加列表L1,即将L和L1合并到L上

    L.sort()                    #对列表L进行排序

    L.reverse()              #对列表L进行倒序

    列表可以进行+运算,相当于extend, 如a = [ 'I', 'love', 'you'], b=[1,2,3] ,a + b = [ 'I', 'love', 'you', 1,2,3]

    列表可以进行*运算,如[1,2]*2 = [1,2,1,2]

    列表中某个元素可以改变,如:a=['I','love','you'] , a[0] = 'i', 那么a =['i', 'love','you']

    关键字del 可以用来删除列表或列表中某元素,如del a[1]      #删除列表中第2个元素。

    列表的复制:

    L1 = L       #L1是L的别名,按C的说法,就是指针地址相同,对L1的操作,就是对L的操作。

    L1 =L[:]     #L1则是L的另一份拷贝。对L1操作,不过影响L。

如下:

>>> a
['I', 'you']
>>> a.insert(1,'love')
>>> a
['I', 'love', 'you']
>>> L1 = a;
>>> L1
['I', 'love', 'you']
>>> L1.pop()
'you'
>>> a
['I', 'love']
>>> 

>>> L1 = a[:]
>>> L1
['I', 'love']
>>> L1.pop()
'love'
>>> a
['I', 'love']
>>> 

   新建列表

>>> testList = [10086, '中国移动',[1,2,3,4]]

>>> testList = [10086, '中国移动',[1,2,3,4]]
>>> print len(testList)  #访问列表长度
3
>>> print testList[1:]  #到列表结尾
['\xe4\xb8\xad\xe5\x9b\xbd\xe7\xa7\xbb\xe5\x8a\xa8', [1, 2, 3, 4]]
>>> testList.append('i\'m new here!')
>>> print len(testList)
4
>>> testList
[10086, '\xe4\xb8\xad\xe5\x9b\xbd\xe7\xa7\xbb\xe5\x8a\xa8', [1, 2, 3, 4], "i'm new here!"]
>>> print testList[-1]
i'm new here!
>>> print testList.pop(1) #弹出元素
中国移动
>>> print len(testList)
3
>>> testList
[10086, [1, 2, 3, 4], "i'm new here!"]
>>> 
>>> Matrix = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> print Matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print Matrix[1]
[4, 5, 6]
>>> 
>>> col2 = [row[1] for row in Matrix]
>>> print col2
[2, 5, 8]
>>> col2even = [row[1] for row in Matrix if row[1]%2 ==0]
>>> print col2even
[2, 8]
>>> 


   (4) 字典类型(dict)

    python中的字典和C++中map很像,每一个元素是一对(pair),它包含有key和value两部分。python中字典的key是integer或string类型,value可以任意的类型,并且key(键)是唯一的。

    字典的方法(这里a表示一个字典,如a={'name': ahuang1900, 'age': 24):

    a.get(key, 0)         #和a[key]相同,得到值value.

    a.has_key(key)    #判断是否有键key,返回True或者False

    a.keys()                #返回字典键的列表

    a.values()             #返回字典值的列表

    a.items()               #返回字典对应的列表形式

    a.update(字典)     #

    a.popitem()           #得到一个pair(一元组表示),从字典中删除它

    a.clear()                #清空字典,和del a类似

    a.copy()                #拷贝字典

    cmp(a,b)               #比较字典a和b,第一个大则返回1,小返回-1,一样大返回0,优先级:元素个数->键大小->键值大小

    字典的复制:

     dict1 = dict         #dict1是dict的别名,相对于C++中的引用。

     dict2 = dict.copy()     #字典的另一份拷贝


>>> a
{'age': 24, 'name': 'ahuang1900'}
>>> a.get('age',0)
24
>>> a['age']
24
>>> a.has_key('age')
True
>>> a.keys()
['age', 'name']
>>> a.values()
[24, 'ahuang1900']
>>> a.items()
[('age', 24), ('name', 'ahuang1900')]
>>> a
{'age': 24, 'name': 'ahuang1900'}
>>> a.popitem()
('age', 24)
>>> a
{'name': 'ahuang1900'}
>>> a.copy()
{'name': 'ahuang1900'}
>>> b={'age':23,'name':'suky'}
>>> cmp(a,b)
-1
>>> c = a
>>> c
{'name': 'ahuang1900'}
>>> c.clear()
>>> a
{}
>>> 

   新建一个字典

>>> testDict={'time':'时间', 'mathine':'机器','time machine':'时间机器'}
>>> print testDict
{'mathine': '\xe6\x9c\xba\xe5\x99\xa8', 'time machine': '\xe6\x97\xb6\xe9\x97\xb4\xe6\x9c\xba\xe5\x99\xa8', 'time': '\xe6\x97\xb6\xe9\x97\xb4'}
>>> 

  另一种构造字典的方式

>>> newDict ={}
>>> newDict['stuff'] = 'start'
>>> print newDict
{'stuff': 'start'}
>>> newDict['name'] = 'hellen'
>>> print newDict
{'stuff': 'start', 'name': 'hellen'}
>>> 

字典的属性可以是字典和列表

>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'}
... ,'job': ['dev','mgr'],
... 'age':40.5}
>>> print rec
{'age': 40.5, 'job': ['dev', 'mgr'], 'name': {'last': 'Smith', 'first': 'Bob'}}
>>> 

字典排序

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> print D
{'a': 1, 'c': 3, 'b': 2}
>>> for i in sorted(D):
...     print i
...     print D[i]
... 
a
1
b
2
c
3
>>> 

这里需要注意python的对齐方式。

另外通常

squares = [x**2 for x in [1,2,3,4,5]]

要比

>>> squares=[]
>>> for x in [1,2,3,4,5]:
...     squares.append(x**2)
...

更快!!


查看字典中是否存在某个key,可以使用has_key函数

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> E = {'a': 1, 'b': 2, 'e': 4}
>>> 
>>> if not D.has_key('f'):
...     print 'missing'
... 
missing
>>> if D.has_key('a'):
...     print 'haha'
... 
haha
>>> 


   (5) 元组类型

    元组类型和列表类型类似,但是,像number和string一样它具有不变性


    新建元组

>>> testTuple = (1,2,3,4,5)
>>> testTuple 
(1, 2, 3, 4, 5)
>>> 
>>> print len(testTuple)
5
>>> 


  不变性

  (1)字符串的不变性,不能修改字符串中的某个字符

>>> someStr = 'hellen'
>>> someStr 
'hellen'
>>> someStr[1] ='H'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> 

  (2)元组的不变性,即不能修改元组的元素的值

>>> testTuple = (1,2,3,4,5)
>>> testTuple
(1, 2, 3, 4, 5)
>>> testTuple[0] = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> 

   需要注意的是:列表和字典是可以改变值的









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值