第二部分:python 常用操作与函数

2.1,交换两数据
>> a,b = b,a

2.2,去掉list中的重复元素
>> list1 = [1,2,3,2,3,2,5,6]
>> list1 = list(set(list1))

2.3,翻转字符串
>> list1=[5,4,2,2,2,5,3,8]
>> list1=list1[::-1]

2.4,字符串转列表
>> lst="idyjg12"
>> lst = list(lst

2.5 判断一个对象的类型: isinstance(OBJECT, TYPE/CLASS/TUPLE)
示例:判断一个对象是可迭代对象,使用collections模块的Iterable类型判断
>>> from collections import Iterable
>>> string = "abc"
>>> isinstance(string, Iterable) # string是否可迭代 :TRUE
>>> import string
>>> isinstance("sat", str)

2.6 python re模块中match()与search()的区别
两个函数都是用来匹配字符串的,
但match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;search匹配整个字符串,直到找到一个匹配
示例:
>>> import re
>>> re.match(r'python','Programing Python, should be pythonic')
>>> obj1 = re.match(r'python','Programing Python, should be pythonic') #返回None
>>> obj2 = re.search(r'python','Programing Python, should be pythonic') #找到pythonic

2.7 sorted()与sort()
sorted()是内建函数(安装好python后就能使用的函数,不需要导入模块),而sort()是list类型的内建函数list.sort()
sorted使用的是字典序,其返回类型是一个已排序的列表。
a.sort() 已改变其结构,b = a.sort() 是错误的写法! 而 sorted(a, ...)并没有改变a的结构
示例:
(1)字符串排序(使用的是字典序)
"""sorted()按照字典序排序"""
lis = ['a','c','z','E','T','C','b','A','Good','Tack']
print sorted(lis) #['A', 'C', 'E', 'Good', 'Tack', 'a', 'b', 'c', 't‘, 'z']
lis.sort() #['A', 'C', 'E', 'Good', 'Tack', 'a', 'b', 'c', 't', 'z'] //????

2.8 shuffle(): 将序列的所有元素随机排列
>>> import random
>>> random.shuffle(lst)

2.9 type(OBJECT):查看对象类型

原文地址:https://www.cnblogs.com/lifeinsmile/p/5285062.html