一、三元运算


格式:

变量=值1 if 条件 else 值二


Example 1:

a=3

name = "wang" if a == 2 else "zhang"

print name


Example 2:

a=input("pls input a num: ")

print "OK" if a == 2 else "NO"


二、pycharm断点调试:

先在关键地方打上断点后,运行debug模式,此时到第一个断点的行会显示高亮,则表示此处将被执行,但尚未执行,再点下继续,才会执行此行;另外在下方会有一个Debugger窗口,此处放置此断点处所有的变量值,Console窗口显示的是执行的输出结果。


三、python中一切皆对象

一切都是对象,对象是由类创建的。

比如列表的类list,比如:

mylist=[1,33,'wang']

mylist就是列表类的实例化,并且它还具有list类的所有功能,比如append,pop等。


通过type()查看对象的类型

通过dir()查看对象的所有功能

help()查看对象的源码,详细的功能。


四、数据类型的内置方法

1、int 整型


int型默认为10进制,比如:

i=10

i=int(10)

也可以更改进制,如:

b=int("1101",base=2)

print "b is %s" % b


e=int("E",base=16)

print e


整型的内置功能,用dir()可以看到:

['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']


2、str 字符型

str的内置功能,用dir()函数可以看到:

['__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']


 常用功能:

1、首字母大写

2、内容居中

>>> name='wang'

>>> name.center(30)

'             wang             '

>>> name.center(20,"*")

'********wang********'

3、找子序列个数

>>> name='wangwjfajewljfsjdfjgweljgweg'

>>> name.count("j")

6

查找name变量中j出现的次数。


4、编码和解码

UTF-8 -->解码-->unicode -->编码 -->UTF-8

GBK -->解码-->unicode -->编码 -->GBK

decode是解码

encode是编码


5、endswith:判断以哪个字符串结尾。

>>> name='Bright'

>>> name.endswith('t')     #以t结尾的

True

>>> name.startswith('B')   ##以B开头的。

True

6、expandtabs() 

把字符串中的一个tab键转换成空格,默认为8个,也可以指定个数:

name=' Bright'

print name.expandtabs()   #默认为8个

print name.expandtabs(15)    #指定为15个

print name.expandtabs(0)    #如果是0,表示删除tab


查找字符串下标find:

>>> name='  Bright'

>>> name.find('g')       ##查找g的下标

5

>>> name.find('a')       ##返回-1表示没找到

-1

第二种查找下标注index:

>>> name='Bright'

>>> name.index('r')

1

index找不到会报错,find则不会报错,它返回-1.

判断是否为字母或数字:

>>> name.isalnum()

True   #bool值

>>> name.isalpha()     ##判断是否为字母

True

>>> name.isdigit()      ##判断是否为数字

False


>>> a='23523'

>>> a.isdigit()

True

>>> name.islower()   ##判断是否为小字

False

>>> a='   '

>>> a.isspace()      ##判断字符是否为空格

True


>>> name

'i am is tian'

>>> name.title()      ##将字符变成标题

'I Am Is Tian'

>> b=name.title()

>>> b.istitle()      ##判断是否为标题

True

>>> b.isupper()     ##判断字符是否全大写

False


join 表示将列表变成字符串,指定连接符:

>>> li=["cheng","wang"]

>>> '@'.join(li)

'cheng@wang'


>>> name.ljust(30,'0')     #ljust表示左对齐,第一个参数表示长度,第二个填个充值

'i am is tian000000000000000000'   #rjust表示右对齐


>>> b

'I Am Is Tian

>>> b.swapcase()      ##将字符串大小写转换。

'i aM iS tIAN'


lower将字符大写变小写,upper将小写变大写。

strip表示将字符两边空格都移除,lstrip只移除左边空白,rstrip移除右边空白。

rfind从右边开始查找,find是从左边开始查找。



>> b

'I Am Is Tian'

>>> b.partition('Is')   ##用Is来分割字符串为三部分,变成元组

('I Am ', 'Is', ' Tian')


>>> b

'I Am Is Tian'

>>> b.replace('Is','')  ##replace替换字符串中所有匹配项。

'I Am  Tian'


>>> c

'I Am Is Tian\nI Am Is Tian'    ##换行分割。

>>> c.splitlines()

['I Am Is Tian', 'I Am Is Tian']


对应表转换或删除:translate

>>> import string

>>> intab='aeiou'

>>> outtab='12345'     ##intab和outtab是对应表,上下一一对应替换。

>>> trantab=string.maketrans(intab,outtab)      #maketrans将关系合并生成trantab

>>> str='this is string example,do you know'     #str为字符串

>>> print str.translate(trantab,'sm')      ##trantab当成参数传入,'sm'为要删除的字符。

th3 3 tr3ng 2x1pl2,d4 y45 kn4w


#######################################################################

字符串格式化:

 name="I am is {0},age is {1}"

>>> name.format('Bright',30)

'I am is Bright,age is 30'

以下方法也可以:

>>> name.format(nn='Bright',age=29)  #此处键值可以颠倒顺序。

'I am is Bright,age is 29'

用列表传参也可:加一颗*

>>> li=['Bright',32]

>>> name="I am is {0},age is {1}"

>>> name.format(*li)

'I am is Bright,age is 32'

用字典传参:加两颗*

>>> dic={"nn":"Bright","age":29}

>>> name="I am is {nn},age is {age}"   ##注意,此处字典的Key必须和这里的形参相同

>>> name.format(**dic)

'I am is Bright,age is 29'



五、列表

增:append

li.append('new')

删除:del li[1]  #按下标来删除


统计指定元素的个数:count

>>> li=['ww','uu','yp','hh','ww','uu','ww']

>>> li.count('ww')

3


extend: 扩展列表,将两个列表合并,如果把自己传进去就表示列表内容翻倍。

>>> li2=[11,54]

>>> li.extend(li2)

>>> li

['ww', 'uu', 'yp', 'hh', 'ww', 'uu', 'ww', 11, 54]


index表示找到指定元素下标:

>>> li.index('yp')

2


insert表示在指定的位置插入元素。

>>> li.insert(4,'tian')

>>> li

['ww', 'uu', 'yp', 'hh', 'tian', 'ww', 'uu', 'ww', 11, 54]


pop表示删除并返回指定下标的值,若不指定默认为最后一个:

>>> li.pop()

54

>>>name= li.pop(4)

'tian'


remove通过指定元素来删除,不返回值:

>>> li.remove('uu')

>>> li

['ww', 'yp', 'hh', 'uu', 'ww', 11]


#删除列表中元素的方法有:pop,remove和del.


reverse表示给列表元素反转位置:

>>> li.reverse()

>>> li

[11, 'ww', 'uu', 'hh', 'yp', 'ww']


sort表示排序,数字按从小到大,字母按ACSII码来排序。

>>> li

[11, 'ww', 'uu', 'hh', 'yp', 'ww', 11, 'ww', 'uu', 'hh', 'yp', 'ww']

>>> li.sort()

>>> li

[11, 25, 'hh', 'hh', 'uu', 'uu', 'ww', 'ww', 'ww', 'ww', 'yp', 'yp']


六、元组

只有两个方法:

index查询下标

元组[0],通过下标查询元素

count统计元组中元素出现的次数


元组的元素不能被修改,但是元组的元素的元素可以被修改,比如,元组中包括有列表或字典:

>>> tur

('wang', [11, 11, 25, 38, 'hh', 'hh', 'tian', 'uu', 'uu', 'ww', 'ww', 'ww', 'ww', 'yp'])

>>> tur[1].remove('ww')

>>> tur

('wang', [11, 11, 25, 38, 'hh', 'hh', 'tian', 'uu', 'uu', 'ww', 'ww', 'ww', 'yp'])

元组可以转换为列表:

>>> tu=(32,53,'wang')

>>> lis=list(tu)

>>> lis

[32, 53, 'wang']



七、字典

清除字典内容:clear

>>> dic2

{'chen': '1234', 'liu': '9876', 'wang': '4567', 'zhang': '1573'}

>>> dic2.clear()

>>> dic2

{}


浅拷贝:copy


get表示根据key获取value:

>>> dic2.get('chen')

'1234'

如果指定key不存在,则返回None:

>>> print dic2.get('bright')

None

也可指定返回内容:

>>> print dic2.get('bright','不存在')

不存在


字典的key可以是字符、数字和类的实例,也可以是元组,但一般不用元组:

>>> dic2[4]='chang'

>>> dic2

{4: 'chang', 'wang': '4567', (3, 45): 'QWE', 'zhang': '1573', 'liu': '9876', 'chen': '1234'}


判断一个对象是否为字典:

>>> type(dic2) is dict

True


生成字典fromkeys:

>>> dic3

{}

>>> dic3.fromkeys([2,4,'ww'],'bright')

{'ww': 'bright', 2: 'bright', 4: 'bright'}


has_key表示判断字典是否有指定的key:

>>> dic3

{4: 'chang', 'wang': '4567', 'zhang': '1573', (3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}

>>> dic3.has_key('wang')

True


items表示把字典中的每一组key value都指定到一个元组中然后再放入一个大列表中,可以用for循环提取key values:

>>> dic3.items()

[(4, 'chang'), ('wang', '4567'), ('zhang', '1573'), ((3, 45), 'QWE'), ('liu', '9876'), ('chen', '1234')]

>>> for x,y in dic3.items():

...     print x

...     print y

备注,此方法只适合小字典,数据量在十万以上的字典不宜使用,可以使用以下方法:

>>> for x in dic2:print x ,dic2[x]

4 chang

wang 4567


iteritems和iterkeys、itervalues是迭代使用,在大数据循环中使用。

keys表示取键,values表示获取全部的值。

product_dic={'apple':30,'peal':50,'banace':80}

##打印索引

product_dic.keys()    

['banace', 'peal', 'apple']

>>> product_dic.values()

[80, 50, 30]




pop表示删除指定的key,并返回value的值。

>>> dic2.pop('wang')

'4567'


popitem表示随便删除一些key value值。

>>> dic2.popitem()

('zhang', '1573')

>>> dic2

{(3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}


setdefault查找字典中如果有该key则返回value,如果不存在,则自动设置,如果存在设置的value不生效,还是原来的:

>>> dic2

{(3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}

>>> dic2.setdefault('liu')

'9876'

>>> dic2.setdefault('wang','333')

'333'

>>> dic2

{'wang': '333', (3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}

>>> dic2.setdefault('wang','555')

'333'


update用于将两个字典合并,如果有重复的key,则以update中的字典的value为准:

>>> dic

{4: 'chang', 'wang': '4567', 'zhang': '1573', (3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}

>>> dic2

{'wang': '333', (3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}

>>> dic.update(dic2)

>>> dic

{4: 'chang', 'wang': '333', 'zhang': '1573', (3, 45): 'QWE', 'liu': '9876', 'chen': '1234'}


copy拷贝字典:

>>> for i in range(6):dic2[i]=[]

>>> dic2

{0: [], 1: [], 2: [], 3: [], 4: [], 5: []}

>>> dic2[1].append({"B":1})

>>> dic2

{0: [], 1: [{'B': 1}], 2: [], 3: [], 4: [], 5: []}

>>> dic4=dic2   #把一个字典中的值赋值给另一个字典

>>> dic4

{0: [], 1: [{'B': 1}], 2: [], 3: [], 4: [], 5: []}

>>> dic4['tian']='wang'   #当另一个字典发生改变时,原来的字典也会改变,如果是变量则不会。

>>> dic4

{0: [], 1: [{'B': 1}], 2: [], 3: [], 4: [], 5: [], 'tian': 'wang'}

>>> dic2

{0: [], 1: [{'B': 1}], 2: [], 3: [], 4: [], 5: [], 'tian': 'wang'}



八、集合:


>>> li

[1, 3, 'www', 53, 22, 1, 'www']

>>> set1=set(li)

>>> set1

set([1, 'www', 3, 53, 22])         ##集合功能之一,去重。集合是无序的

>>> a

set(['a', 'c', 'b'])

>>> b=set(['a','d','e','t'])

>>> a|b

set(['a', 'c', 'b', 'e', 'd', 't'])     ## | 竖线符号可以把a和b两个集合数值连起来

>>> a-b

set(['c', 'b'])        ##a集合减b集合,会得到a里有的数值b里没有。

>>> a^b

set(['c', 'b', 'e', 'd', 't'])   #对称差积,将两个集合中没有的数值组合起来,将共同有的丢掉

>>> a & b

set(['a'])          ##只把a集合和b集合中共有的数据列出来

>>> b.add(54)         ##add给集合中增加数据

>>> b.add('ww')  

>>> b

set(['a', 'e', 'd', 'ww', 't', 54])

>>> b.update('ABC')       ##update会将数据分成单个字符添加到集合中,只能增加字符

>>> b

set(['a', 'A', 'C', 'B', 'e', 'd', 'ww', 't', 54])     

>>> b.remove('A')

>>> b.remove('B')

>>> b.remove('ww')

>>> b

set(['a', 'C', 'e', 'd', 't', 54])          ##remove删除数据

>> set1

set([1, 'www', 3, 53, 22])

>>> set1.pop()

1

>>> set1

set(['www', 3, 53, 22])        ##pop为随机删除集合中的数据并返回值

>>> set1.pop()

'www'

>>> set1

set([3, 53, 22])


判断集合的子集和父集:

>>> set3

set(['www', 53])

>>> set1

set([1, 'www', 3, 53, 22])

>>> set3.issubset(set1)        #issubset用来判断子集

True

>>> set1.issuperset(set3)    #issuperset判断是否为父集

True


















从下内容不明所以:

>>> dic2=dic2.fromkeys(range(6),[])

>>> dic2

{0: [], 1: [], 2: [], 3: [], 4: [], 5: []}

>>> dic2[1].append({"B":{}})  #此步骤是生成以下内容是由于fromkeys引起的。

>>> dic2

{0: [{'B': {}}], 1: [{'B': {}}], 2: [{'B': {}}], 3: [{'B': {}}], 4: [{'B': {}}], 5: [{'B': {}}]}