2.2-2.7 python基础笔记 细讲数据类型

业无高卑志当坚,男儿有求安得闲?这篇文章主要讲述2.2-2.7 python基础笔记 细讲数据类型相关的知识,希望能为你提供帮助。
2.2上节补充:身份运算和none 身份运算

> > > name = "Alex" > > > age = 13 > > > name "Alex" > > > > > > type(name),type(age) (< class \'str\'> ,< class \'int\'> )

判断一个数据类型是不是str,or int等, 可以用身份运算符is
运算符 描述 实例
is is 是判断两个标识符是不是引用自一个对象 x is y,类似id(x) == id(y),如果引用的是同一类,返回True,否则返回False
is not is not 是判断两个标识符是不是引用于不同对象 x is not y ,类似id(x) != id(y),如果引用的类型不一样结果为True,否则返回False
None空 Empty
name = None age = None weight = None height = Noneif name is None: == print("你还没起名字")

三元运算?
a = 10 b = 5 if a > 15 : c = a else: c = bd = a if a > 15 else b d = 值1 if 条件A else 值2 #如果条件A成立,就取左边值1,不行取值2

2.3细讲数据类型:列表第一讲我们大概介绍了列表的基本用法,本节我们学习下
再回顾一下列表的特点:
列表操作人物:Alex,Egon,old_vill_age_master,Peiqi,black_girl
names = ["Alex","Egon","old_vill_age_master","peiqi","black_girl"] print(names) print(names[0])

增加操作 插入,可插入任何位置
names.insert(4,"Alex")

追加,数据会增加到尾部
names.append("luocat")

合并,可以把另一列表的值合并起来
PC=["Jobs","Bill","Guido"] names.extend(PC)

列表嵌套
name.insert(2,["jobs","Bill","Guido"]) names[2][1]

删除操作 del 直接删
del names[-1]

pop 删
names.pop() #默认删除最后一个元素并返回被删除的值 names.pop(1) #删除指定元素

clean 清空
PC.clean()

remove 操作
name.remove("Alex") #删除离第0个最近的值,如果没有就会报错

修改操作
names[-1]= "黑姑娘"

查操作
names.index("Alex") #返回从左开始匹配到的第一个Alex的索引 names.count("Alex") #返回Alex的个数

命令嵌套
del names[names,index("peiqi")]

切片切片就像切面包,可以同时取出元素的多个值
names[start:end] names[1:4] # 不包含下标4的值

倒着切
> > > names[-5:-1] [\'Alex\',\'Egon\',\'peiqi\',\'Guido\']

很简单,把-5+-1=-6就ok了
排序& 翻转 排序
> > > a = [9,5,8,7,6,4,3,1,2] > > > a.sort() > > > a [1,2,3,4,5,6,7,8,9]

下面的排序结果如何解释???
> > > names = [ \'金角大王\',\'rain\',\'@\',\'黑姑娘\',\'狗蛋\',\'4\',\'#\',\'银角大王\',\'eva\'] > > > names.sort() > > > names [\'#\',\'4\',\'@\',\'eva\',\'rain\',\'狗蛋\',\'金角大王\',\'银角大王\',\'黑姑娘\' ]

以后会讲
实现从右往左走
a[-1:-5:-1] [\'Guido\',\'peiqi\',\'Egon\',\'Alex\']

列表反转
> > > a[::-1] [9,8,7,6,5,4,3,2,1,0]

循环列表
> > > for i in names: ...print(i) ... 黑姑娘 银角大王 金角大王 狗蛋 rain eva @ 4 #

2.4细讲数据类型:元组
> > > names = (\'alex\',\'jack\')

除了无法修改,元组很多地方都和列表神似,所以按照列表的操作就可以了
[^注意:元组本身不可变,如果元组中还包含其他可变元素,这些可变元素可以改变]:
> > > data = https://www.songbingjia.com/android/(11,22,33,44,55,66,77,88,99[/'alex\',\'bill\']) > > > data (11,22,33,44,55,66,77,88,99[\'alex\',\'bill\']) > > > data[9][1] = \'Guido\' > > > data (11,22,33,44,55,66,77,88,99[\'alex\',\'Guido\'])

?........................................................
?\'alex\'\'bill\'
?........................................................
?|
?|
?........................................................................
?(11,22,33,44,55,66,77,88,99[(列表地址)])
?........................................................................
2.5细讲数据类型:字符串 定义字符串是一个有序的字符的集合,用来存储和表示基本的文本信息,\' \'或" " 或\'\'\' \'\'\'中间包含的内容称之为字符串
创建
hello = "hello,Guido! how are you?"

特性?1.按照从左到右的顺序定义字符集合,下标从0开始访问,有序
  1. strhello
    索引01234
3.可以进行切片操作
4.不可变,字符串是不可变的不能像列表一样修改其中某个元素,所有对字符串的修改操作其实都是相当于生成了一份新数据
字符串的常用操作
[^capitalize(self)]:
[^casefold(self)]:
[^center(self,width,fillchar=None)]:
[^count(self,sub,start=None,end=None)]:
[^endswith(self,suffix,start=None,and=None)]:
[^find(self,sub,start=None,end=None)]:
[^format(self,*args,**kwargs)]:
[^format_map(self,mapping)]:
[^index(self,sub,start=None,end=None)]:
[^isdigit(self)]:
[^islower(self)]:
[^isspase(self)]:
[^isupper(self)]:
[^join(self,iterable)]:
[^ijust(self,chars=None)]:
[^lower(self)]:
[^istrip(self,width,fillchar)]:
[^replace(self,old,new,count)]:
[^ rjust(self,width,fillchar = None)]:
[^rsplit(self,sep=None,maxsplit=-1)]:
[^rstrip(self,chars=None)]:
[^split(self,sep=None,maxsplit= -1)]:
[^startswith(self,prefix,start=None,end=None)]:
[^strip(self,chars=None)]:
[^swapcase(self)]:
[^upper(self)]:
[^zfill(self,width) ]:
def capitalize(self): \'首字母大写\' def casefold(self): \'把字符串全变小写\' > > > c = \'Alex Zhang\' > > > c.casefold() \'alex zhang\' def center(self,width,fillchar=None): > > > c.center(50,"-") \'-------------------------alex zhang-------------------------\' def couth(self,sub,start=None,end=None): """ S.couth(sub[,start[end]]) -> int> > > s = "welcome to apeland" > > > s.couth(\'e\') 3 > > > s.couth(\'e\',3) 2 > > > s.count(\'e\',3,-1) 2 def encode(self,encoding = \'utf-8\',errors=\'strict\'): """ \'编码,日后讲\'def endwith(self,suffix,start=None,end=None): > > > s = "welcome to apeland" > > > s.endwith("land")#判断以什么结尾 True def find(self,sub,start=None,end=None): """ S.find(sub[,start[,end]]) -> intReturn the lowest index in S where substring sub is found, such that sub is conained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.Return -1 on failure. """ return 0 def format(self,*args,**kwargs): # known special case of str.format > > > s = "Welcome{0} to Apeland,you are No.{1} user" > > > s.format("Eva",9999) \'Welcome Eva to Apeland.you are No.9999 user,\'> > > s1 = "Welcome {name} to Apeland.you are No.{user_num} user." > > > s1.fornat(name="Alex",user_num = 999) \'Welcome Alex to Apeland.you are No.999 user\'def format_map(self,mapping): """ S.format_map(mapping) -> strReturn a formatted version of S. using substitutions from mapping. The substtutions are identified by braces(\'and\'). """ \'讲完dict再讲这个\' def index(self,sub,start=None,end=None): """ S.index(sub[,start[,end]]) -> intReturn the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.Raises ValueError when the substring is not found. """ def isdigit(self): """ S.isdigit() -> boolReturn True if all characters in S are digits and there is at least one charaters in S, False otherwise. """ return Falsedef islow(self): """ S.islower() -> bollReturn True if all cased characters in S are lowercase and there is at least one cased charater in S, False otherwise """def isspace(self): """ S.isspace() -> boolReturn True if all characters in S are whitespace and there is at least one character in S, False otherwise """ def isupper(self): """ S.isupper() -> boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S,False otherwise """ def join(self,iterable): """ S.join(iterable) -> strReturn a string which is the concatenation of the strings in the iterable. The sparator between element is S. """ > > > n = [\'alex\',\'jack\',\'rain\'] > > > \'l\'.join(n) \'alexljacklrain\' def ljust(self,width,fillchar-None): """ S.Ijust(width[,fillchar]) -> strReturn S left-justtified in a Unicode string of lenght width Padding is done using the specified fill charater(default is a space) """ return "" def lower(self): """ S.lower() -> strReturn a copy of thr string S converter to lowercase """ return "" def lstrip(self,chars=None): """ S.letrip([chars]) -> strReturn a copy of the string S with leading whitespace rerroved. If chars is given and not None, remove characters in chars instedd. """ return "" def replace(self,old,new,count=None): """ S.replace(old,new[,count]) -> strReturn a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given only the first count occurrences are replaced. """ return "" def rjust(self,width,fillchar=None): """ S.rjust(width[,fillchar]) -> strReturn S right-justified in a string of length width.padding is done using the specified fill charatar (default is a space) """ return "" def rsplit(self,sep=None,maxsplit = -1): """ S.rsplit(sep=None,maxsplit=-1) -> list of stringsReturn a list of the words in 5 using sep as the delinter string. staring at the end of the end of the string and working to the front. If max split is given, at most max split splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def split(self,sep=None,maxsplit=-1): """ S.split(sep=None,maxsplit=-1) -> list of stringsReturn a list of the words in S using sep as the deliniter string. If max split is given, at most max split splits are done If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result """ return [] def startswith(self,prefix,start=None,end=None): """ S.startswith(perfix[,start[,end]]) -> bool Return True if S starts with the specified prefix,False otherwise. With optional start. test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try """ return False def strip(self,chars=None): """ S.strip([chars]) -> strReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None, remove characters in chars instedd. """ return "" def swapcase(self): """ S.swapcase() -> strReturn a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def upper(self): """ S.upper() -> strReturn a copy of S converted to uppercase """ return "" def zfill(self,width): """ S.zfill(width) -> strpad a numeric string S with zeros on the left, to fill a field of the specified width. The string S never truncated """ return ""

2.6细讲数据类型:字典:
staff_list = [ ["Alex",23,"CEO",50000] ["Edge",36,"行政",4000] ["peiqi",26,"讲师",20000] #[xxx,xx,xx,xxx] #[xxx,xx,xx,xxx] #[xxx,xx,xx,xxx] ]

这样存没问题,不过你要查一个人的工资的话是不是得把列表遍历一遍
for i in staff_list: if i [0] == \'黑姑娘\': print(i) break

定义【2.2-2.7 python基础笔记 细讲数据类型】{key1:value1,key2,value2}
1.键与值用冒号":"分开 2.项与项用逗号","分开

创建操作
> > > person = {"name":"alex",\'age\':20} #或 > > > person = dict(name = \'seven\',age = 20) #或 > > > person = dict({"name":"egon",\'age\':20})#或 > > > {}.fromkeys([1,2,3,4,5,6,7,8,9]) {1:100,2:100,3:100,4:100,5:100,6:100,7:100,8:100,9:100}

增加操作
names = { "Alex":[23,"CEO",66000], "黑姑娘":[24,"行政",4000] } #新增key names["佩奇"] = [26,"讲师",40000] names.setdefault("oldboy",[50,"boss",100000]) #D.setdefault(k[,d]) -> D.get(k[,d]),also set D[k]=d if k not in D

删除操作
names.pop("Alex") #删除指定key names.popitem() #随便删除一个key del names["oldboy"] #删除指定key,同pop方法 names.clear() #清空dict

修改操作
dic[\'key\'] = \'new_value\'#如果key在字典中存在,\'new_value\'将会代替原来的value值; dic.update(dic2)#将字典dic2的键值对添加到字典dic中

查操作
dic[\'key\'] #返回字典中key对应的值,若key不存在字典中,就报错 dic.get(key,default = None) #返回字典中key对应的值,若key不存在字典中,则返回default的值 \'key\' in dic #若存在返回True,没有则返回Falsedic.keys() #返回一个包含字典所有Key的列表 dic.valuea() #返回一个包含字典所有value的列表; dic.itema() #返回一个包含所有(键,值)元组的列表

循环
for k in dic.keys() for k,v in dic items() for k in dic # 推荐用这种,效率速度最快 info = { "name":"51cto", "Mission":"being a charging station for it people", "website":" http://edu.51cto.com " } for k in info: print(k,info[k]) #输出 name 51cto Mission being a charging station for it people website http://edu.51cto.com

求长度
len(dic)

2.7细讲数据类型:集合 定义集合和我们所学的列表有点像,也可以存一堆数据,不过他有几个独特的特点,令其在整个python语言里占有一席之地
基于上面的特性,我们可以用集合来干两件事,去重和关系运算
语法 创建集合
> > > a = {1,2,3,4,2,\'Alex\',3,\'rain\',\'Alex\'} > > > a {1,2,3,4,\'Alex\',\'rain\'}

由于它是天生去重的,重复的值你根本存不进去
帮列表去重帮列表去重最快速的方法是什么?就是把它转成集合,去重完,再转回列表
> > > b [1,2,3,4,2,\'Alex\',3,\'rain\',\'Alex\'] > > > set(b) {1,2,3,4,\'alex\',\'rain\'} > > > > > > b = list(set(b)) > > > b [1,2,3,4,\'Alex\',\'rain\']

增删改查
> > > a {1,2,3,4\'alex\',\'rain\'}# 新增 a.add(\'blackgirl\')#删除disccard > > > a {2,3,\'blackgirl\',\'Alex\',\'rain\'} > > > a.discard(\'rain\') #删除一个存在的值 > > > a.discard(\'oldboy\') #如果这个值不存在,do nothing. > > > a {2,3,\'blackgirl\',\'Alex\'} > > > #随机删除,少用,或特定场景用 > > > a.pop()#删除并返回 1#删除remove > > > a.remove(4)#查 > > > a {2,3,\'blackgirl\',\'Alex\'} > > > \'Alex\' in a True#改 \'\'\'呵呵,不能改...\'\'\'

关系运算
the51cto = {"peiqi","oldboy","seapeak","Ma JJ","Old village head","Black girl","Alex"}luffycity= {"Alex","Egon","Rain","Ma JJ","Nick","Jack"}print(the51cto & luffycity) #交集,elements in both setprint(the51cto | ) #并集 or 合集print(the51cto -luffycity) #差集,only in 51cto print( luffycity - the51cto) # 差集, only in luffycityprint(the51cto ^ luffycity) # 对称差集,把脚踩2只船的人T出去

两个集合之间一般有三种关系,相交,包含,不相交。在python中分别用下面的方法判断:
print(the51cto.isdisjoint(luffycity)) #判断2个集合是不是不相交,返回True of False print(the51cto.issubset(luffycity)) #判断the51cto是不是luffycity的子集,返回True of False print(the51cto.issuperset(luffycity))#判断the51cto是不是luffycity的父集,返回True of False


    推荐阅读