python中表达式4+0.5值的数据类型为_Python之路【第五篇】:Python基本数据类型

type函数

利用type()函数可以查看数据的类型,比如说是str类型,在编辑器中写上str,按住ctrl,点击str,

就到了源码定义的部分,所有str的功能都在这里了,同样,对于一个str变量temp,temp.upper(),

按住ctrl,点击temp.upper()也跳到了这个功能的说明部分

所有字符串或者数字、字典等数据类型所具备的方法都存在相对应的类里面

查看对象的类,或对象所具备的功能

1、可以利用type查看类型,利用ctrl+鼠标左键

2、利用dir(对象名字),可以查看该类对象所具有的功能名字

3、help(对象名字)或者help(type(对象名字)),可以查看详细说明

4、直接ctrl+鼠标左键点击方法名字,便会自动定位到功能处

下面是对数据类型中的一些函数进行说明,只说了一些不太好理解的函数

在函数的源码里面,如果括号中只有一个self,就表示不用传参数

dir()函数

见type函数部分

help()函数

见type函数部分

强制类型转换

数据类型(变量),例如,有一个str型变量temp,将其转换成int型:

int(temp)

数据类型中,字符串、列表、字典无疑是最重要的

数字

int型变量

在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

int型变量的创建:

n1 = 123

n2 = int(123)

类里面有一个__init__方法,类名()这种形式实际上就是调用了该方法,通过查看源码我们也看到,int('0ff',16),这样可以将16进制转化为10进制,这个知道就好了

还有就是类里面带有下划线的方法是自动调用的,在学习到类的时候会有详述

思考一个问题:n1=123,n2=123与n1=123,n2=n1有何区别?

答:n1=123,n2=123是指向内存中的两块区域,n1=123,n2=n1指向内存中的一块区域,但是在python内部,为了内存优化,在一个数值范围内(-5~257),都是指向一块内存。可以用过id(n1)与id(n2)来查看内存地址

python真的很人性化,之前的一些编程语言,整数大小分为多种,但是在python中,在低版本中,还会考虑数据的长度问题,32位机器: -2**31~2**31 ,64位机器:-2**63~2**63-1,如果超出了这个范围,python内部会自动变为long类型,而long是电脑多牛逼,long就有多大,所以在python中使用int,不用担心长度的限制,但是在3的版本中,就没有这个限制了,int就是无限长了,再也不用考虑长度问题了,爽爆了,看下面:

n = 1234567891012312321312312131231231231231

print(n/2327343993898989893493498239489238483248)

输出:0.5304621466567329

是不是感觉爽爆了,哈哈,我喜欢

int类型常用功能剖析:

1、n1+n2 实际是调用n1.__add__(n2)这个方法

2、bit_length()表示该数字的二进制最少可以占用几位

3、输出十进制数字的二进制用bin()方法,具体参考Python之路【第九篇】

1 classint(object)2 | int(x=0) ->integer3 | int(x, base=10) ->integer4 |

5 | Convert a number or string to an integer, or return 0 ifno arguments6 | are given. If x is a number, return x.__int__(). For floating point7 |numbers, this truncates towards zero.8 |

9 | If x is not a number or if base isgiven, then x must be a string,10 | bytes, or bytearray instance representing an integer literal inthe11 | given base. The literal can be preceded by '+' or '-' andbe surrounded12 | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.13 | Base 0 means to interpret the base fromthe string as an integer literal.14 | >>> int('0b100', base=0)15 | 4

16 |

17 |Methods defined here:18 |

19 | __abs__(self, /)20 |abs(self)21 |

22 | __add__(self, value, /)23 | Return self+value.24 |

25 | __and__(self, value, /)26 | Return self&value.27 |

28 | __bool__(self, /)29 | self !=030 |

31 | __ceil__(...)32 |Ceiling of an Integral returns itself.33 |

34 | __divmod__(self, value, /)35 |Return divmod(self, value).36 |

37 | __eq__(self, value, /)38 | Return self==value.39 |

40 | __float__(self, /)41 |float(self)42 |

43 | __floor__(...)44 |Flooring an Integral returns itself.45 |

46 | __floordiv__(self, value, /)47 | Return self//value.48 |

49 | __format__(...)50 |default object formatter51 |

52 | __ge__(self, value, /)53 | Return self>=value.54 |

55 | __getattribute__(self, name, /)56 |Return getattr(self, name).57 |

58 | __getnewargs__(...)59 |

60 | __gt__(self, value, /)61 | Return self>value.62 |

63 | __hash__(self, /)64 |Return hash(self).65 |

66 | __index__(self, /)67 | Return self converted to an integer, if self is suitable foruse as an index into a list.68 |

69 | __int__(self, /)70 |int(self)71 |

72 | __invert__(self, /)73 | ~self74 |

75 | __le__(self, value, /)76 | Return self<=value.77 |

78 | __lshift__(self, value, /)79 | Return self<

81 | __lt__(self, value, /)82 | Return self

84 | __mod__(self, value, /)85 | Return self%value.86 |

87 | __mul__(self, value, /)88 | Return self*value.89 |

90 | __ne__(self, value, /)91 | Return self!=value.92 |

93 | __neg__(self, /)94 | -self95 |

96 | __new__(*args, **kwargs) frombuiltins.type97 | Create and return a new object. See help(type) foraccurate signature.98 |

99 | __or__(self, value, /)100 | Return self|value.101 |

102 | __pos__(self, /)103 | +self104 |

105 | __pow__(self, value, mod=None, /)106 |Return pow(self, value, mod).107 |

108 | __radd__(self, value, /)109 | Return value+self.110 |

111 | __rand__(self, value, /)112 | Return value&self.113 |

114 | __rdivmod__(self, value, /)115 |Return divmod(value, self).116 |

117 | __repr__(self, /)118 |Return repr(self).119 |

120 | __rfloordiv__(self, value, /)121 | Return value//self.122 |

123 | __rlshift__(self, value, /)124 | Return value<

126 | __rmod__(self, value, /)127 | Return value%self.128 |

129 | __rmul__(self, value, /)130 | Return value*self.131 |

132 | __ror__(self, value, /)133 | Return value|self.134 |

135 | __round__(...)136 |Rounding an Integral returns itself.137 |Rounding with an ndigits argument also returns an integer.138 |

139 | __rpow__(self, value, mod=None, /)140 |Return pow(value, self, mod).141 |

142 | __rrshift__(self, value, /)143 | Return value>>self.144 |

145 | __rshift__(self, value, /)146 | Return self>>value.147 |

148 | __rsub__(self, value, /)149 | Return value-self.150 |

151 | __rtruediv__(self, value, /)152 | Return value/self.153 |

154 | __rxor__(self, value, /)155 | Return value^self.156 |

157 | __sizeof__(...)158 | Returns size in memory, inbytes159 |

160 | __str__(self, /)161 |Return str(self).162 |

163 | __sub__(self, value, /)164 | Return self-value.165 |

166 | __truediv__(self, value, /)167 | Return self/value.168 |

169 | __trunc__(...)170 |Truncating an Integral returns itself.171 |

172 | __xor__(self, value, /)173 | Return self^value.174 |

175 |bit_length(...)176 | int.bit_length() ->int177 |

178 | Number of bits necessary to represent self inbinary.179 | >>> bin(37)180 | '0b100101'

181 | >>> (37).bit_length()182 | 6

183 |

184 |conjugate(...)185 |Returns self, the complex conjugate of any int.186 |

187 | from_bytes(...) frombuiltins.type188 | int.from_bytes(bytes, byteorder, *, signed=False) ->int189 |

190 |Return the integer represented by the given array of bytes.191 |

192 | The bytes argument must be a bytes-like object (e.g. bytes orbytearray).193 |

194 |The byteorder argument determines the byte order used to represent the195 | integer. If byteorder is 'big', the most significant byte isat the196 | beginning of the byte array. If byteorder is 'little', the most197 | significant byte isat the end of the byte array. To request the native198 | byte order of the host system, use `sys.byteorder'as the byte order value.

199 |

200 | The signed keyword-only argument indicates whether two's complement is

201 |used to represent the integer.202 |

203 |to_bytes(...)204 | int.to_bytes(length, byteorder, *, signed=False) ->bytes205 |

206 |Return an array of bytes representing an integer.207 |

208 | The integer is represented using length bytes. An OverflowError is

209 | raised if the integer is notrepresentable with the given number of210 |bytes.211 |

212 |The byteorder argument determines the byte order used to represent the213 | integer. If byteorder is 'big', the most significant byte isat the214 | beginning of the byte array. If byteorder is 'little', the most215 | significant byte isat the end of the byte array. To request the native216 | byte order of the host system, use `sys.byteorder'as the byte order value.

217 |

218 | The signed keyword-only argument determines whether two's complement is

219 | used to represent the integer. If signed is False anda negative integer220 | is given, an OverflowError israised.221 |

222 | ----------------------------------------------------------------------

223 |Data descriptors defined here:224 |

225 |denominator226 | the denominator of a rational number inlowest terms227 |

228 |imag229 |the imaginary part of a complex number230 |

231 |numerator232 | the numerator of a rational number inlowest terms233 |

234 |real235 | the real part of a complex number

int

bytes类型:

在2.7中没有,在3里面才有,将字符转换成字节,返回一个字节的集合,所以说3真的是很强大,具体可以参考Python之路【第九篇】

布尔值

True  真

False   假

字符串(str)

字符串的创建:

s1 = 'asd'

s2 = str()创建一个空字符串

s3 = str('asd')创建一个普通的字符串

s4 = str(字节类型,编码),如b_gbk = bytes(s,encoding='gbk')        str(b_gbk,encoding='gbk')

str类型常用功能剖析:

1、format(),format()中接受的参数,依次传递给字符串中的占位符{0},{1},{2},如:s='hello,{0},I {1} you',s.format('python','love')

最后s就变成hello python,I love you有几个占位符就要给format()传递几个参数

2、join(),如lst=['h','e','l','l','o'],执行'_'.join(lst)后得到h_e_l_l_o

3、lstrip()移除字符串中左边的空格

4、rstrip()移除字符串中右边的空格

5、strip()移除字符串中的左边跟右边的空格

6、partition()将字符串进行分割

7、replace()对指定的内容进行替换

8、split()对字符串进行分割

9、索引s='abcde',s[0]表示第一个字符,s[1]表示第二个字符,依此类推,len(s)用来获取字符串的长度,即字符个数

10、切片s[n:m] n=

1 classstr(object)2 | str(object='') ->str3 | str(bytes_or_buffer[, encoding[, errors]]) ->str4 |

5 | Create a new string object from the given object. If encoding or

6 | errors isspecified, then the object must expose a data buffer7 | that will be decoded using the given encoding anderror handler.8 | Otherwise, returns the result of object.__str__() (ifdefined)9 | orrepr(object).10 |encoding defaults to sys.getdefaultencoding().11 | errors defaults to 'strict'.12 |

13 |Methods defined here:14 |

15 | __add__(self, value, /)16 | Return self+value.17 |

18 | __contains__(self, key, /)19 | Return key inself.20 |

21 | __eq__(self, value, /)22 | Return self==value.23 |

24 | __format__(...)25 | S.__format__(format_spec) ->str26 |

27 |Return a formatted version of S as described by format_spec.28 |

29 | __ge__(self, value, /)30 | Return self>=value.31 |

32 | __getattribute__(self, name, /)33 |Return getattr(self, name).34 |

35 | __getitem__(self, key, /)36 |Return self[key].37 |

38 | __getnewargs__(...)39 |

40 | __gt__(self, value, /)41 | Return self>value.42 |

43 | __hash__(self, /)44 |Return hash(self).45 |

46 | __iter__(self, /)47 |Implement iter(self).48 |

49 | __le__(self, value, /)50 | Return self<=value.51 |

52 | __len__(self, /)53 |Return len(self).54 |

55 | __lt__(self, value, /)56 | Return self

58 | __mod__(self, value, /)59 | Return self%value.60 |

61 | __mul__(self, value, /)62 | Return self*value.n63 |

64 | __ne__(self, value, /)65 | Return self!=value.66 |

67 | __new__(*args, **kwargs) frombuiltins.type68 | Create and return a new object. See help(type) foraccurate signature.69 |

70 | __repr__(self, /)71 |Return repr(self).72 |

73 | __rmod__(self, value, /)74 | Return value%self.75 |

76 | __rmul__(self, value, /)77 | Return self*value.78 |

79 | __sizeof__(...)80 | S.__sizeof__() -> size of S in memory, inbytes81 |

82 | __str__(self, /)83 |Return str(self).84 |

85 |capitalize(...)86 | S.capitalize() ->str87 |

88 |Return a capitalized version of S, i.e. make the first character89 | have upper case andthe rest lower case.90 |

91 |casefold(...)92 | S.casefold() ->str93 |

94 | Return a version of S suitable forcaseless comparisons.95 |

96 |center(...)97 | S.center(width[, fillchar]) ->str98 |

99 | Return S centered in a string of length width. Padding is

100 | done using the specified fill character (default isa space)101 |

102 |count(...)103 | S.count(sub[, start[, end]]) ->int104 |

105 | Return the number of non-overlapping occurrences of substring sub in

106 | string S[start:end]. Optional arguments start andend are107 | interpreted as inslice notation.108 |

109 |encode(...)110 | S.encode(encoding='utf-8', errors='strict') ->bytes111 |

112 | Encode S using the codec registered forencoding. Default encoding113 | is 'utf-8'. errors may be given to set a different error114 | handling scheme. Default is 'strict' meaning that encoding errors raise

115 | a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and

116 | 'xmlcharrefreplace'as well as any other name registered with117 |codecs.register_error that can handle UnicodeEncodeErrors.118 |

119 |endswith(...)120 | S.endswith(suffix[, start[, end]]) ->bool121 |

122 | Return True ifS ends with the specified suffix, False otherwise.123 |With optional start, test S beginning at that position.124 |With optional end, stop comparing S at that position.125 | suffix can also be a tuple of strings to try.126 |

127 |expandtabs(...)128 | S.expandtabs(tabsize=8) ->str129 |

130 |Return a copy of S where all tab characters are expanded using spaces.131 | If tabsize is not given, a tab size of 8 characters isassumed.132 |

133 |find(...)134 | S.find(sub[, start[, end]]) ->int135 |

136 | Return the lowest index in S where substring sub isfound,137 | such that sub iscontained within S[start:end]. Optional138 | arguments start and end are interpreted as inslice notation.139 |

140 | Return -1on failure.141 |

142 |format(...)143 | S.format(*args, **kwargs) ->str144 |

145 | Return a formatted version of S, using substitutions from args andkwargs.146 | The substitutions are identified by braces ('{' and '}').147 |

148 |format_map(...)149 | S.format_map(mapping) ->str150 |

151 | Return a formatted version of S, using substitutions frommapping.152 | The substitutions are identified by braces ('{' and '}').153 |

154 |index(...)155 | S.index(sub[, start[, end]]) ->int156 |

157 | Like S.find() but raise ValueError when the substring is notfound.158 |

159 |isalnum(...)160 | S.isalnum() ->bool161 |

162 | Return True if all characters inS are alphanumeric163 | and there is at least one character inS, False otherwise.164 |

165 |isalpha(...)166 | S.isalpha() ->bool167 |

168 | Return True if all characters inS are alphabetic169 | and there is at least one character inS, False otherwise.170 |

171 |isdecimal(...)172 | S.isdecimal() ->bool173 |

174 | Return True if there are only decimal characters inS,175 |False otherwise.176 |

177 |isdigit(...)178 | S.isdigit() ->bool179 |

180 | Return True if all characters inS are digits181 | and there is at least one character inS, False otherwise.182 |

183 |isidentifier(...)184 | S.isidentifier() ->bool185 |

186 | Return True if S isa valid identifier according187 |to the language definition.188 |

189 | Use keyword.iskeyword() to test forreserved identifiers190 | such as "def" and "class".191 |

192 |islower(...)193 | S.islower() ->bool194 |

195 | Return True if all cased characters in S are lowercase and there is

196 | at least one cased character inS, False otherwise.197 |

198 |isnumeric(...)199 | S.isnumeric() ->bool200 |

201 | Return True if there are only numeric characters inS,202 |False otherwise.203 |

204 |isprintable(...)205 | S.isprintable() ->bool206 |

207 | Return True if all characters inS are considered208 | printable in repr() or S isempty, False otherwise.209 |

210 |isspace(...)211 | S.isspace() ->bool212 |

213 | Return True if all characters inS are whitespace214 | and there is at least one character inS, False otherwise.215 |

216 |istitle(...)217 | S.istitle() ->bool218 |

219 | Return True if S is a titlecased string and there isat least one220 | character in S, i.e. upper- andtitlecase characters may only221 | follow uncased characters andlowercase characters only cased ones.222 |Return False otherwise.223 |

224 |isupper(...)225 | S.isupper() ->bool226 |

227 | Return True if all cased characters in S are uppercase and there is

228 | at least one cased character inS, False otherwise.229 |

230 |join(...)231 | S.join(iterable) ->str232 |

233 | Return a string which is the concatenation of the strings inthe234 | iterable. The separator between elements isS.235 |

236 |ljust(...)237 | S.ljust(width[, fillchar]) ->str238 |

239 | Return S left-justified in a Unicode string of length width. Padding is

240 | done using the specified fill character (default isa space).241 |

242 |lower(...)243 | S.lower() ->str244 |

245 |Return a copy of the string S converted to lowercase.246 |

247 |lstrip(...)248 | S.lstrip([chars]) ->str249 |

250 |Return a copy of the string S with leading whitespace removed.251 | If chars is given and not None, remove characters inchars instead.252 |

253 |partition(...)254 | S.partition(sep) ->(head, sep, tail)255 |

256 | Search for the separator sep in S, and returnthe part before it,257 | the separator itself, and the part after it. If the separator is not

258 | found, return S andtwo empty strings.259 |

260 |replace(...)261 | S.replace(old, new[, count]) ->str262 |

263 |Return a copy of S with all occurrences of substring264 | old replaced by new. If the optional argument count is

265 |given, only the first count occurrences are replaced.266 |

267 |rfind(...)268 | S.rfind(sub[, start[, end]]) ->int269 |

270 | Return the highest index in S where substring sub isfound,271 | such that sub iscontained within S[start:end]. Optional272 | arguments start and end are interpreted as inslice notation.273 |

274 | Return -1on failure.275 |

276 |rindex(...)277 | S.rindex(sub[, start[, end]]) ->int278 |

279 | Like S.rfind() but raise ValueError when the substring is notfound.280 |

281 |rjust(...)282 | S.rjust(width[, fillchar]) ->str283 |

284 | Return S right-justified in a string of length width. Padding is

285 | done using the specified fill character (default isa space).286 |

287 |rpartition(...)288 | S.rpartition(sep) ->(head, sep, tail)289 |

290 | Search for the separator sep in S, starting at the end of S, and return

291 | the part before it, the separator itself, andthe part after it. If the292 | separator is not found, return two empty strings andS.293 |

294 |rsplit(...)295 | S.rsplit(sep=None, maxsplit=-1) ->list of strings296 |

297 | Return a list of the words inS, using sep as the298 | delimiter string, starting at the end of the string and

299 | working to the front. If maxsplit isgiven, at most maxsplit300 | splits are done. If sep is notspecified, any whitespace string301 | isa separator.302 |

303 |rstrip(...)304 | S.rstrip([chars]) ->str305 |

306 |Return a copy of the string S with trailing whitespace removed.307 | If chars is given and not None, remove characters inchars instead.308 |

309 |split(...)310 | S.split(sep=None, maxsplit=-1) ->list of strings311 |

312 | Return a list of the words inS, using sep as the313 | delimiter string. If maxsplit isgiven, at most maxsplit314 | splits are done. If sep is not specified or isNone, any315 | whitespace string is a separator andempty strings are316 | removed fromthe result.317 |

318 |splitlines(...)319 | S.splitlines([keepends]) ->list of strings320 |

321 | Return a list of the lines inS, breaking at line boundaries.322 | Line breaks are not included inthe resulting list unless keepends323 | is given andtrue.324 |

325 |startswith(...)326 | S.startswith(prefix[, start[, end]]) ->bool327 |

328 | Return True ifS starts with the specified prefix, False otherwise.329 |With optional start, test S beginning at that position.330 |With optional end, stop comparing S at that position.331 | prefix can also be a tuple of strings to try.332 |

333 |strip(...)334 | S.strip([chars]) ->str335 |

336 | Return a copy of the string S with leading andtrailing337 |whitespace removed.338 | If chars is given and not None, remove characters inchars instead.339 |

340 |swapcase(...)341 | S.swapcase() ->str342 |

343 |Return a copy of S with uppercase characters converted to lowercase344 | andvice versa.345 |

346 |title(...)347 | S.title() ->str348 |

349 |Return a titlecased version of S, i.e. words start with title case350 |characters, all remaining cased characters have lower case.351 |

352 |translate(...)353 | S.translate(table) ->str354 |

355 | Return a copy of the string S inwhich each character has been mapped356 |through the given translation table. The table must implement357 | lookup/indexing via __getitem__, for instance a dictionary orlist,358 | mapping Unicode ordinals to Unicode ordinals, strings, orNone. If359 | this operation raises LookupError, the character isleft untouched.360 |Characters mapped to None are deleted.361 |

362 |upper(...)363 | S.upper() ->str364 |

365 |Return a copy of S converted to uppercase.366 |

367 |zfill(...)368 | S.zfill(width) ->str369 |

370 |Pad a numeric string S with zeros on the left, to fill a field371 | of the specified width. The string S isnever truncated.372 |

373 | ----------------------------------------------------------------------

374 |Static methods defined here:375 |

376 | maketrans(x, y=None, z=None, /)377 | Return a translation table usable forstr.translate().378 |

379 | If there isonly one argument, it must be a dictionary mapping Unicode380 | ordinals (integers) or characters to Unicode ordinals, strings orNone.381 |Character keys will be then converted to ordinals.382 | If there are two arguments, they must be strings of equal length, and

383 | in the resulting dictionary, each character inx will be mapped to the384 | character at the same position in y. If there isa third argument, it385 | must be a string, whose characters will be mapped to None in the result.

str

列表(list)

列表是元素的集合,并且列表中的元素是可变化的

在以后的日子里,有一个约定俗成的东西,写列表的时候最后加一个逗号,比如:[1,2,3,4,5,]

列表的创建;

li = [1,2,3,4,]

li = list(),创建一个空的列表

li = list(可迭代对象),转换,字符串、元组、字典都是可迭代对象,比如这里的可迭代对象是一个字符串,内部会运行一个for循环,把可迭代对象的元素当作列表的元素,如:

s = 'hello'li=list(s)print(li)

输出结果为:['h', 'e', 'l', 'l', 'o']

dic = {'k1':'as','k2':'dasd'}print(list(dic.values()))print(list(dic.items()))print(list(dic.keys()))

输出结果为:

['dasd', 'as']

[('k2', 'dasd'), ('k1', 'as')]

['k2', 'k1']

list类型常用功能剖析:

lst = [1,2,3,'e'],这就是一个列表

len(lst)获取列表长度

列表中的索引、切片、循环跟字符串都是一样的

append(),在列表末尾追加元素,lst.append('s'),则lst=[***,'s']

count(),统计列表中某一个元素的个数

extend(),扩展列表,lst.extend(iterable),iterable为可迭代对象

index(),获取某个元素的索引

insert(),往某个索引位置插入一个值

pop(),移除一个值,没有参数的,移除尾部的值,但是这个值可以赋给另外一个变量,如a=lst.pop(),就表示将列表中的最后一个元素移除并赋值给a

remove(),移除从左边找到的第一个

reverse(),反转列表

sort()排序

del lst[index]删除索引index处的元素,del lst[index1:index2]

列表的嵌套:li = ['alex',123,{'k1':123,'k2':{'aa':1,'bb':2}}]

列表的切片与索引

1 classlist(object)2 | list() ->new empty list3 | list(iterable) -> new list initialized from iterable's items

4 |

5 |Methods defined here:6 |

7 | __add__(self, value, /)8 | Return self+value.9 |

10 | __contains__(self, key, /)11 | Return key inself.12 |

13 | __delitem__(self, key, /)14 |Delete self[key].15 |

16 | __eq__(self, value, /)17 | Return self==value.18 |

19 | __ge__(self, value, /)20 | Return self>=value.21 |

22 | __getattribute__(self, name, /)23 |Return getattr(self, name).24 |

25 | __getitem__(...)26 | x.__getitem__(y) <==>x[y]27 |

28 | __gt__(self, value, /)29 | Return self>value.30 |

31 | __iadd__(self, value, /)32 | Implement self+=value.33 |

34 | __imul__(self, value, /)35 | Implement self*=value.36 |

37 | __init__(self, /, *args, **kwargs)38 | Initialize self. See help(type(self)) foraccurate signature.39 |

40 | __iter__(self, /)41 |Implement iter(self).42 |

43 | __le__(self, value, /)44 | Return self<=value.45 |

46 | __len__(self, /)47 |Return len(self).48 |

49 | __lt__(self, value, /)50 | Return self

52 | __mul__(self, value, /)53 | Return self*value.n54 |

55 | __ne__(self, value, /)56 | Return self!=value.57 |

58 | __new__(*args, **kwargs) frombuiltins.type59 | Create and return a new object. See help(type) foraccurate signature.60 |

61 | __repr__(self, /)62 |Return repr(self).63 |

64 | __reversed__(...)65 | L.__reversed__() -- returna reverse iterator over the list66 |

67 | __rmul__(self, value, /)68 | Return self*value.69 |

70 | __setitem__(self, key, value, /)71 |Set self[key] to value.72 |

73 | __sizeof__(...)74 | L.__sizeof__() -- size of L in memory, inbytes75 |

76 |append(...)77 | L.append(object) -> None --append object to end78 |

79 |clear(...)80 | L.clear() -> None -- remove all items fromL81 |

82 |copy(...)83 | L.copy() -> list --a shallow copy of L84 |

85 |count(...)86 | L.count(value) -> integer -- returnnumber of occurrences of value87 |

88 |extend(...)89 | L.extend(iterable) -> None -- extend list by appending elements fromthe iterable90 |

91 |index(...)92 | L.index(value, [start, [stop]]) -> integer -- returnfirst index of value.93 | Raises ValueError if the value is notpresent.94 |

95 |insert(...)96 | L.insert(index, object) --insert object before index97 |

98 |pop(...)99 | L.pop([index]) -> item -- remove and returnitem at index (default last).100 | Raises IndexError if list is empty or index isout of range.101 |

102 |remove(...)103 | L.remove(value) -> None --remove first occurrence of value.104 | Raises ValueError if the value is notpresent.105 |

106 |reverse(...)107 | L.reverse() -- reverse *IN PLACE*

108 |

109 |sort(...)110 | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

111 |

112 | ----------------------------------------------------------------------

113 | Data andother attributes defined here:114 |

115 | __hash__ = None

list

元组(tuple)

元组的创建:

t=(1,2,3)  创建一个元组

t=tuple([1,2,3])将列表转换为一个元组

tuple类型常用功能剖析 :

tup=(1,2,3,'a')这就是一个元组

元组跟列表几乎是一样的

列表可以进行修改,元组不可以进行修改(不能进行增删改操作)

count()计算元素出现的次数

index()获取指定元素的索引位置

元组的嵌套

1 classlist(object)2 | list() ->new empty list3 | list(iterable) -> new list initialized from iterable's items

4 |

5 |Methods defined here:6 |

7 | __add__(self, value, /)8 | Return self+value.9 |

10 | __contains__(self, key, /)11 | Return key inself.12 |

13 | __delitem__(self, key, /)14 |Delete self[key].15 |

16 | __eq__(self, value, /)17 | Return self==value.18 |

19 | __ge__(self, value, /)20 | Return self>=value.21 |

22 | __getattribute__(self, name, /)23 |Return getattr(self, name).24 |

25 | __getitem__(...)26 | x.__getitem__(y) <==>x[y]27 |

28 | __gt__(self, value, /)29 | Return self>value.30 |

31 | __iadd__(self, value, /)32 | Implement self+=value.33 |

34 | __imul__(self, value, /)35 | Implement self*=value.36 |

37 | __init__(self, /, *args, **kwargs)38 | Initialize self. See help(type(self)) foraccurate signature.39 |

40 | __iter__(self, /)41 |Implement iter(self).42 |

43 | __le__(self, value, /)44 | Return self<=value.45 |

46 | __len__(self, /)47 |Return len(self).48 |

49 | __lt__(self, value, /)50 | Return self

52 | __mul__(self, value, /)53 | Return self*value.n54 |

55 | __ne__(self, value, /)56 | Return self!=value.57 |

58 | __new__(*args, **kwargs) frombuiltins.type59 | Create and return a new object. See help(type) foraccurate signature.60 |

61 | __repr__(self, /)62 |Return repr(self).63 |

64 | __reversed__(...)65 | L.__reversed__() -- returna reverse iterator over the list66 |

67 | __rmul__(self, value, /)68 | Return self*value.69 |

70 | __setitem__(self, key, value, /)71 |Set self[key] to value.72 |

73 | __sizeof__(...)74 | L.__sizeof__() -- size of L in memory, inbytes75 |

76 |append(...)77 | L.append(object) -> None --append object to end78 |

79 |clear(...)80 | L.clear() -> None -- remove all items fromL81 |

82 |copy(...)83 | L.copy() -> list --a shallow copy of L84 |

85 |count(...)86 | L.count(value) -> integer -- returnnumber of occurrences of value87 |

88 |extend(...)89 | L.extend(iterable) -> None -- extend list by appending elements fromthe iterable90 |

91 |index(...)92 | L.index(value, [start, [stop]]) -> integer -- returnfirst index of value.93 | Raises ValueError if the value is notpresent.94 |

95 |insert(...)96 | L.insert(index, object) --insert object before index97 |

98 |pop(...)99 | L.pop([index]) -> item -- remove and returnitem at index (default last).100 | Raises IndexError if list is empty or index isout of range.101 |

102 |remove(...)103 | L.remove(value) -> None --remove first occurrence of value.104 | Raises ValueError if the value is notpresent.105 |

106 |reverse(...)107 | L.reverse() -- reverse *IN PLACE*

108 |

109 |sort(...)110 | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

111 |

112 | ----------------------------------------------------------------------

113 | Data andother attributes defined here:114 |

115 | __hash__ = None

tuple

字典(dict)

字典的创建:

a={..........}

a=dict(k1=123,k2=345)

a=dict(可迭代对象),比如li = [1,2,3],dict(li),不可以,但是dict(enumerate(li))可以

列表元素的添加:

dic['k1']=123或者dic.update({'k1':123}),但是第一种方式更为简单

dict类型常用功能剖析:

user_info = {'sam':1,'Jim':2}这就是一个字典,大括号里面是键值对

索引:user_info['sam']

user_info.keys()获取所有的key

user_info.values()获取所有的value

user_info.items()获取所有的键值对

user_info.clear():清除所有内容

user_info.get(key):根据key获取值,如果key不存在,可以指定一个默认值user_info.get('sas','123'),不存在的键sas,值为123

通过索引也可以获取值,但是get在key不存在的时候返回None,而索引会报错,所以推荐用get

user_info.has_key()检查字典中指定的key是否存在,python2有这个函数python3没有这个函数,用in代替:key in user_info.keys()

user_info.update()批量更新

pop()

popitem()

del user_info(key)删除键值对

循环:默认只输出key

for i in user_info:这句与for i in user_info.keys():是等价的,因为for in in user_info默认是对键进行循环。

print(i)输出key

for k,v in user_info.items():

print(k)输出key

print(v)输出value

1 classdict(object)2 | dict() ->new empty dictionary3 | dict(mapping) -> new dictionary initialized from a mapping object's

4 |(key, value) pairs5 | dict(iterable) -> new dictionary initialized as ifvia:6 | d ={}7 | for k, v initerable:8 | d[k] =v9 | dict(**kwargs) -> new dictionary initialized with the name=value pairs10 | in the keyword argument list. For example: dict(one=1, two=2)11 |

12 |Methods defined here:13 |

14 | __contains__(self, key, /)15 | True if D has a key k, elseFalse.16 |

17 | __delitem__(self, key, /)18 |Delete self[key].19 |

20 | __eq__(self, value, /)21 | Return self==value.22 |

23 | __ge__(self, value, /)24 | Return self>=value.25 |

26 | __getattribute__(self, name, /)27 |Return getattr(self, name).28 |

29 | __getitem__(...)30 | x.__getitem__(y) <==>x[y]31 |

32 | __gt__(self, value, /)33 | Return self>value.34 |

35 | __init__(self, /, *args, **kwargs)36 | Initialize self. See help(type(self)) foraccurate signature.37 |

38 | __iter__(self, /)39 |Implement iter(self).40 |

41 | __le__(self, value, /)42 | Return self<=value.43 |

44 | __len__(self, /)45 |Return len(self).46 |

47 | __lt__(self, value, /)48 | Return self

50 | __ne__(self, value, /)51 | Return self!=value.52 |

53 | __new__(*args, **kwargs) frombuiltins.type54 | Create and return a new object. See help(type) foraccurate signature.55 |

56 | __repr__(self, /)57 |Return repr(self).58 |

59 | __setitem__(self, key, value, /)60 |Set self[key] to value.61 |

62 | __sizeof__(...)63 | D.__sizeof__() -> size of D in memory, inbytes64 |

65 |clear(...)66 | D.clear() -> None. Remove all items fromD.67 |

68 |copy(...)69 | D.copy() ->a shallow copy of D70 |

71 | fromkeys(iterable, value=None, /) frombuiltins.type72 | Returns a new dict with keys from iterable andvalues equal to value.73 |

74 |get(...)75 | D.get(k[,d]) -> D[k] if k in D, elsed. d defaults to None.76 |

77 |items(...)78 | D.items() -> a set-like object providing a view on D's items

79 |

80 |keys(...)81 | D.keys() -> a set-like object providing a view on D's keys

82 |

83 |pop(...)84 | D.pop(k[,d]) -> v, remove specified key and returnthe corresponding value.85 | If key is not found, d is returned if given, otherwise KeyError israised86 |

87 |popitem(...)88 | D.popitem() -> (k, v), remove and returnsome (key, value) pair as a89 | 2-tuple; but raise KeyError if D isempty.90 |

91 |setdefault(...)92 | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not inD93 |

94 |update(...)95 | D.update([E, ]**F) -> None. Update D from dict/iterable E andF.96 | If E is present and has a .keys() method, then does: for k in E: D[k] =E[k]97 | If E is present and lacks a .keys() method, then does: for k, v in E: D[k] =v98 | In either case, this is followed by: for k in F: D[k] =F[k]99 |

100 |values(...)101 | D.values() -> an object providing a view on D's values

102 |

103 | ----------------------------------------------------------------------

104 | Data andother attributes defined here:105 |

106 | __hash__ = None

dict

set

set数据类型:不允许重复的无序集合,所以不能通过下标来取

创建:s = set()空集合,s= {1,2,3,4}

转换:s = set([1,2,3,3])把可迭代对象里面相同的元素都去掉

set的方法:

add() 添加一个元素

clear()将集合清空

difference() ret = se.difference(be),找se中存在,be中不存在的元素,并给新的集合

difference_update 找se中存在,be中不存在的元素,并给新的集合,更新自己

discard()移除指定元素,不存在不报错

remove()移除指定元素,不存在会报错

set1.intersection(set2)交集,并给一个新的集合

set1.intersection_update(set2)交集,并更新自己

set1.isdisjoint(set2),有交集False,没交集True

set1.issubset(set2) set1是不是set2的子序列

set1.issuperset(set2) set1是不是set2的父序列

pop()与remove区别,pop可以拿到返回值(也就是移除的那个元素),remove拿不到

一般来说,字符串执行一个功能,会产生一个新的,原来的不变,列表、元组、字典执行一个功能,一般会自身发生变化

还有一点,在类的源码定义中,

如果没有staticmethod,调用方式为:

对象.方法;

如果有staticmethod,调用方式为:

类.方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值