Python基本数据类型
1. Number(数字)
Python3 支持 int、float、bool、complex(复数)。
在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
1.1 int
1 #!/usr/bin/env python3 2 #print(help(int)) 3 print(dir(int)) 4 var1 = int(-10) 5 var2 = 10 6 var3 = 3 7 print(var1.__abs__()) #取绝对值 8 print(var1.__add__(var2)) #整数相加 9 print(var1.__and__(var2)) #做与运算 10 print(var1.__bool__()) #var != 0 即为True 11 print(int.__ceil__(-1)) #数字的上入整数,int 本来为整数,此处似乎无意义 12 import math 13 print(math.ceil(1.2)) 14 print(math.ceil(-3.2)) 15 print(var2.__divmod__(var3)) #var1 / var3 res=(商,余数) 16 print(var1.__eq__(var2)) #res = "True" if var1 == var2 else "False" 17 print(var1.__float__()) #int to float 18 print(int.__floor__(1)) ##数字的下舍整数,int 本来为整数,此处似乎无意义 19 print(math.floor(1.7)) 20 print(math.floor(-3.2)) 21 print(var2.__floordiv__(var3)) #var1 / var3 res=商 22 print(int.__format__(var3,'3')) #格式化 23 print(var1.__gt__(var2)) #res = "True" if var1 > var2 else "False" 24 print(var1.__invert__()) #取反 25 print(var1.__lt__(var2)) #res = "True" if var1 < var2 else "False" 26 print(var2.__mod__(var3)) #取余 27 print(var2.__mul__(var3)) #乘 28 print(var2.__ne__(var3)) #res = "True" if var1 != var2 else "False" 29 print(var1.__neg__()) #相反数 30 print(var1.__pow__(var3)) #幂
1.2 float
1 class float(object) 2 | float(x) -> floating point number 3 | 4 | Convert a string or number to a floating point number, if possible. 5 | 6 | Methods defined here: 7 | 8 | __abs__(self, /) 9 | abs(self) 10 | 11 | __add__(self, value, /) 12 | Return self+value. 13 | 14 | __bool__(self, /) 15 | self != 0 16 | 17 | __divmod__(self, value, /) 18 | Return divmod(self, value). 19 | 20 | __eq__(self, value, /) 21 | Return self==value. 22 | 23 | __float__(self, /) 24 | float(self) 25 | 26 | __floordiv__(self, value, /) 27 | Return self//value. 28 | 29 | __format__(...) 30 | float.__format__(format_spec) -> string 31 | 32 | Formats the float according to format_spec. 33 | 34 | __ge__(self, value, /) 35 | Return self>=value. 36 | 37 | __getattribute__(self, name, /) 38 | Return getattr(self, name). 39 | 40 | __getformat__(...) from builtins.type 41 | float.__getformat__(typestr) -> string 42 | 43 | You probably don't want to use this function. It exists mainly to be 44 | used in Python's test suite. 45 | 46 | typestr must be 'double' or 'float'. This function returns whichever of 47 | 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the 48 | format of floating point numbers used by the C type named by typestr. 49 | 50 | __getnewargs__(...) 51 | 52 | __gt__(self, value, /) 53 | Return self>value. 54 | 55 | __hash__(self, /) 56 | Return hash(self). 57 | 58 | __int__(self, /) 59 | int(self) 60 | 61 | __le__(self, value, /) 62 | Return self<=value. 63 | 64 | __lt__(self, value, /) 65 | Return self<value. 66 | 67 | __mod__(self, value, /) 68 | Return self%value. 69 | 70 | __mul__(self, value, /) 71 | Return self*value. 72 | 73 | __ne__(self, value, /) 74 | Return self!=value. 75 | 76 | __neg__(self, /) 77 | -self 78 | 79 | __new__(*args, **kwargs) from builtins.type 80 | Create and return a new object. See help(type) for accurate signature. 81 | 82 | __pos__(self, /) 83 | +self 84 | 85 | __pow__(self, value, mod=None, /) 86 | Return pow(self, value, mod). 87 | 88 | __radd__(self, value, /) 89 | Return value+self. 90 | 91 | __rdivmod__(self, value, /) 92 | Return divmod(value, self). 93 | 94 | __repr__(self, /) 95 | Return repr(self). 96 | 97 | __rfloordiv__(self, value, /) 98 | Return value//self. 99 | 100 | __rmod__(self, value, /) 101 | Return value%self. 102 | 103 | __rmul__(self, value, /) 104 | Return value*self. 105 | 106 | __round__(...) 107 | Return the Integral closest to x, rounding half toward even. 108 | When an argument is passed, work like built-in round(x, ndigits). 109 | 110 | __rpow__(self, value, mod=None, /) 111 | Return pow(value, self, mod). 112 | 113 | __rsub__(self, value, /) 114 | Return value-self. 115 | 116 | __rtruediv__(self, value, /) 117 | Return value/self. 118 | 119 | __setformat__(...) from builtins.type 120 | float.__setformat__(typestr, fmt) -> None 121 | 122 | You probably don't want to use this function. It exists mainly to be 123 | used in Python's test suite. 124 | 125 | typestr must be 'double' or 'float'. fmt must be one of 'unknown', 126 | 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be 127 | one of the latter two if it appears to match the underlying C reality. 128 | 129 | Override the automatic determination of C-level floating point type. 130 | This affects how floats are converted to and from binary strings. 131 | 132 | __str__(self, /) 133 | Return str(self). 134 | 135 | __sub__(self, value, /) 136 | Return self-value. 137 | 138 | __truediv__(self, value, /) 139 | Return self/value. 140 | 141 | __trunc__(...) 142 | Return the Integral closest to x between 0 and x. 143 | 144 | as_integer_ratio(...) 145 | float.as_integer_ratio() -> (int, int) 146 | 147 | Return a pair of integers, whose ratio is exactly equal to the original 148 | float and with a positive denominator. 149 | Raise OverflowError on infinities and a ValueError on NaNs. 150 | 151 | >>> (10.0).as_integer_ratio() 152 | (10, 1) 153 | >>> (0.0).as_integer_ratio() 154 | (0, 1) 155 | >>> (-.25).as_integer_ratio() 156 | (-1, 4) 157 | 158 | conjugate(...) 159 | Return self, the complex conjugate of any float. 160 | 161 | fromhex(...) from builtins.type 162 | float.fromhex(string) -> float 163 | 164 | Create a floating-point number from a hexadecimal string. 165 | >>> float.fromhex('0x1.ffffp10') 166 | 2047.984375 167 | >>> float.fromhex('-0x1p-1074') 168 | -5e-324 169 | 170 | hex(...) 171 | float.hex() -> string 172 | 173 | Return a hexadecimal representation of a floating-point number. 174 | >>> (-0.1).hex() 175 | '-0x1.999999999999ap-4' 176 | >>> 3.14159.hex() 177 | '0x1.921f9f01b866ep+1' 178 | 179 | is_integer(...) 180 | Return True if the float is an integer. 181 | 182 | ---------------------------------------------------------------------- 183 | Data descriptors defined here: 184 | 185 | imag 186 | the imaginary part of a complex number 187 | 188 | real 189 | the real part of a complex number
1.3 bool
1 class bool(int) 2 | bool(x) -> bool 3 | 4 | Returns True when the argument x is true, False otherwise. 5 | The builtins True and False are the only two instances of the class bool. 6 | The class bool is a subclass of the class int, and cannot be subclassed. 7 | 8 | Method resolution order: 9 | bool 10 | int 11 | object 12 | 13 | Methods defined here: 14 | 15 | __and__(self, value, /) 16 | Return self&value. 17 | 18 | __new__(*args, **kwargs) from builtins.type 19 | Create and return a new object. See help(type) for accurate signature. 20 | 21 | __or__(self, value, /) 22 | Return self|value. 23 | 24 | __rand__(self, value, /) 25 | Return value&self. 26 | 27 | __repr__(self, /) 28 | Return repr(self). 29 | 30 | __ror__(self, value, /) 31 | Return value|self. 32 | 33 | __rxor__(self, value, /) 34 | Return value^self. 35 | 36 | __str__(self, /) 37 | Return str(self). 38 | 39 | __xor__(self, value, /) 40 | Return self^value. 41 | 42 | ---------------------------------------------------------------------- 43 | Methods inherited from int: 44 | 45 | __abs__(self, /) 46 | abs(self) 47 | 48 | __add__(self, value, /) 49 | Return self+value. 50 | 51 | __bool__(self, /) 52 | self != 0 53 | 54 | __ceil__(...) 55 | Ceiling of an Integral returns itself. 56 | 57 | __divmod__(self, value, /) 58 | Return divmod(self, value). 59 | 60 | __eq__(self, value, /) 61 | Return self==value. 62 | 63 | __float__(self, /) 64 | float(self) 65 | 66 | __floor__(...) 67 | Flooring an Integral returns itself. 68 | 69 | __floordiv__(self, value, /) 70 | Return self//value. 71 | 72 | __format__(...) 73 | default object formatter 74 | 75 | __ge__(self, value, /) 76 | Return self>=value. 77 | 78 | __getattribute__(self, name, /) 79 | Return getattr(self, name). 80 | 81 | __getnewargs__(...) 82 | 83 | __gt__(self, value, /) 84 | Return self>value. 85 | 86 | __hash__(self, /) 87 | Return hash(self). 88 | 89 | __index__(self, /) 90 | Return self converted to an integer, if self is suitable for use as an index into a list. 91 | 92 | __int__(self, /) 93 | int(self) 94 | 95 | __invert__(self, /) 96 | ~self 97 | 98 | __le__(self, value, /) 99 | Return self<=value. 100 | 101 | __lshift__(self, value, /) 102 | Return self<<value. 103 | 104 | __lt__(self, value, /) 105 | Return self<value. 106 | 107 | __mod__(self, value, /) 108 | Return self%value. 109 | 110 | __mul__(self, value, /) 111 | Return self*value. 112 | 113 | __ne__(self, value, /) 114 | Return self!=value. 115 | 116 | __neg__(self, /) 117 | -self 118 | 119 | __pos__(self, /) 120 | +self 121 | 122 | __pow__(self, value, mod=None, /) 123 | Return pow(self, value, mod). 124 | 125 | __radd__(self, value, /) 126 | Return value+self. 127 | 128 | __rdivmod__(self, value, /) 129 | Return divmod(value, self). 130 | 131 | __rfloordiv__(self, value, /) 132 | Return value//self. 133 | 134 | __rlshift__(self, value, /) 135 | Return value<<self. 136 | 137 | __rmod__(self, value, /) 138 | Return value%self. 139 | 140 | __rmul__(self, value, /) 141 | Return value*self. 142 | 143 | __round__(...) 144 | Rounding an Integral returns itself. 145 | Rounding with an ndigits argument also returns an integer. 146 | 147 | __rpow__(self, value, mod=None, /) 148 | Return pow(value, self, mod). 149 | 150 | __rrshift__(self, value, /) 151 | Return value>>self. 152 | 153 | __rshift__(self, value, /) 154 | Return self>>value. 155 | 156 | __rsub__(self, value, /) 157 | Return value-self. 158 | 159 | __rtruediv__(self, value, /) 160 | Return value/self. 161 | 162 | __sizeof__(...) 163 | Returns size in memory, in bytes 164 | 165 | __sub__(self, value, /) 166 | Return self-value. 167 | 168 | __truediv__(self, value, /) 169 | Return self/value. 170 | 171 | __trunc__(...) 172 | Truncating an Integral returns itself. 173 | 174 | bit_length(...) 175 | int.bit_length() -> int 176 | 177 | Number of bits necessary to represent self in binary. 178 | >>> bin(37) 179 | '0b100101' 180 | >>> (37).bit_length() 181 | 6 182 | 183 | conjugate(...) 184 | Returns self, the complex conjugate of any int. 185 | 186 | from_bytes(...) from builtins.type 187 | int.from_bytes(bytes, byteorder, *, signed=False) -> int 188 | 189 | Return the integer represented by the given array of bytes. 190 | 191 | The bytes argument must be a bytes-like object (e.g. bytes or bytearray). 192 | 193 | The byteorder argument determines the byte order used to represent the 194 | integer. If byteorder is 'big', the most significant byte is at the 195 | beginning of the byte array. If byteorder is 'little', the most 196 | significant byte is at the end of the byte array. To request the native 197 | byte order of the host system, use `sys.byteorder' as the byte order value. 198 | 199 | The signed keyword-only argument indicates whether two's complement is 200 | used to represent the integer. 201 | 202 | to_bytes(...) 203 | int.to_bytes(length, byteorder, *, signed=False) -> bytes 204 | 205 | Return an array of bytes representing an integer. 206 | 207 | The integer is represented using length bytes. An OverflowError is 208 | raised if the integer is not representable with the given number of 209 | bytes. 210 | 211 | The byteorder argument determines the byte order used to represent the 212 | integer. If byteorder is 'big', the most significant byte is at the 213 | beginning of the byte array. If byteorder is 'little', the most 214 | significant byte is at the end of the byte array. To request the native 215 | byte order of the host system, use `sys.byteorder' as the byte order value. 216 | 217 | The signed keyword-only argument determines whether two's complement is 218 | used to represent the integer. If signed is False and a negative integer 219 | is given, an OverflowError is raised. 220 | 221 | ---------------------------------------------------------------------- 222 | Data descriptors inherited from int: 223 | 224 | denominator 225 | the denominator of a rational number in lowest terms 226 | 227 | imag 228 | the imaginary part of a complex number 229 | 230 | numerator 231 | the numerator of a rational number in lowest terms 232 | 233 | real 234 | the real part of a complex number
1.4 complex
1 class complex(object) 2 | complex(real[, imag]) -> complex number 3 | 4 | Create a complex number from a real part and an optional imaginary part. 5 | This is equivalent to (real + imag*1j) where imag defaults to 0. 6 | 7 | Methods defined here: 8 | 9 | __abs__(self, /) 10 | abs(self) 11 | 12 | __add__(self, value, /) 13 | Return self+value. 14 | 15 | __bool__(self, /) 16 | self != 0 17 | 18 | __divmod__(self, value, /) 19 | Return divmod(self, value). 20 | 21 | __eq__(self, value, /) 22 | Return self==value. 23 | 24 | __float__(self, /) 25 | float(self) 26 | 27 | __floordiv__(self, value, /) 28 | Return self//value. 29 | 30 | __format__(...) 31 | complex.__format__() -> str 32 | 33 | Convert to a string according to format_spec. 34 | 35 | __ge__(self, value, /) 36 | Return self>=value. 37 | 38 | __getattribute__(self, name, /) 39 | Return getattr(self, name). 40 | 41 | __getnewargs__(...) 42 | 43 | __gt__(self, value, /) 44 | Return self>value. 45 | 46 | __hash__(self, /) 47 | Return hash(self). 48 | 49 | __int__(self, /) 50 | int(self) 51 | 52 | __le__(self, value, /) 53 | Return self<=value. 54 | 55 | __lt__(self, value, /) 56 | Return self<value. 57 | 58 | __mod__(self, value, /) 59 | Return self%value. 60 | 61 | __mul__(self, value, /) 62 | Return self*value. 63 | 64 | __ne__(self, value, /) 65 | Return self!=value. 66 | 67 | __neg__(self, /) 68 | -self 69 | 70 | __new__(*args, **kwargs) from builtins.type 71 | Create and return a new object. See help(type) for accurate signature. 72 | 73 | __pos__(self, /) 74 | +self 75 | 76 | __pow__(self, value, mod=None, /) 77 | Return pow(self, value, mod). 78 | 79 | __radd__(self, value, /) 80 | Return value+self. 81 | 82 | __rdivmod__(self, value, /) 83 | Return divmod(value, self). 84 | 85 | __repr__(self, /) 86 | Return repr(self). 87 | 88 | __rfloordiv__(self, value, /) 89 | Return value//self. 90 | 91 | __rmod__(self, value, /) 92 | Return value%self. 93 | 94 | __rmul__(self, value, /) 95 | Return value*self. 96 | 97 | __rpow__(self, value, mod=None, /) 98 | Return pow(value, self, mod). 99 | 100 | __rsub__(self, value, /) 101 | Return value-self. 102 | 103 | __rtruediv__(self, value, /) 104 | Return value/self. 105 | 106 | __str__(self, /) 107 | Return str(self). 108 | 109 | __sub__(self, value, /) 110 | Return self-value. 111 | 112 | __truediv__(self, value, /) 113 | Return self/value. 114 | 115 | conjugate(...) 116 | complex.conjugate() -> complex 117 | 118 | Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j. 119 | 120 | ---------------------------------------------------------------------- 121 | Data descriptors defined here: 122 | 123 | imag 124 | the imaginary part of a complex number 125 | 126 | real 127 | the real part of a complex number
2.str(字符串)
1 #!/usr/bin/env python 2 3 print(dir(str)) 4 str1 = "hello\tkugou!hello kugou!" 5 print(str1.capitalize()) #S.capitalize() 首字母大写 6 print(str1.casefold()) #S.casefold() lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用casefold()方法 7 print(str1.center(30,'*')) #S.center(width[, fillchar]) 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。 8 print(str1.count('o',2,-1)) #S.count(sub[, start[, end]]) -> int 9 print(str1.encode(encoding='utf-8')) #S.encode(encoding='utf-8', errors='strict') -> bytes 10 print(str1.endswith('gou!')) #S.endswith(suffix[, start[, end]]) -> bool 11 print(str1.endswith('lo',0,5)) #S.endswith(suffix[, start[, end]]) -> bool 12 print(str1.expandtabs(tabsize=4)) #S.expandtabs(tabsize=8) -> str 使原字符串中的制表符("\t")的使用空间变大。使用空格来扩展空间。 13 print(str1.find('he')) #S.find(sub[, start[, end]]) -> int 检测str是否包含在string中,如果beg和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 14 print("{} love {}.".format('ht','NB')) #字符串格式化 15 print("{0} love {1}.".format('ht','NB')) 16 print("{who} love {daughter}.".format(who="ht",daughter='NB')) 17 dic1 = {"who":"ht","daughter":"NB",} 18 print("{who} love {daughter}.".format(**dic1)) 19 print("{0[0]} love {0[1]}.".format(['ht','NB',])) 20 print("{who} love {daughter}.".format_map(dic1)) 21 22 print(str1.index('lo')) #S.index(sub[, start[, end]]) -> int 返回子集合第一次出现的索引位置. start,end 指定查询范围.否则报错 23 print(str1.index('lo',5)) 24 25 print(str1.isalnum()) #S.isalnum() -> bool 至少有一个字符且如果S中的所有字符都是字母数字,那么返回结果就是True;否则,就返回False 26 print(str1.isalpha()) #S.isalpha() -> bool 至少有一个字符且如果S中的所有字符都是字母,那么返回结果就是True;否则,就返回False 27 print(str1.isdecimal()) #S.isdecimal() -> bool 检查字符串是否只包含十进制字符 28 print(str1.isdigit()) #S.isdigit() -> bool 中至少有一个字符且如果S中的所有字符都是数字,那么返回结果就是True;否则,就返回False 29 print(str1.isidentifier()) #S.isidentifier() -> bool 用于判断字符串是否是有效的 Python 标识符,可用来判断变量名是否合法。 30 print(str1.islower()) #S.islower() -> bool 至少有一个字符且如果S中的所有字符都是小写,那么返回结果就是True;否则,就返回False 31 print(str1.isnumeric()) #S.isnumeric() -> bool unicode对象字符串是否只由数字组成 32 print(str1.isprintable()) #S.isprintable() -> bool 所有字符均为可打印字符 33 print(" ".isspace()) #S.isspace() -> bool 至少有一个字符且如果S中的所有字符都是空格,那么返回结果就是True;则,就返回False 34 print("Hello Kugou".istitle()) #S.istitle() -> bool 35 print("ASDFA123".isupper()) #S.isupper() -> bool 至少有一个字符且如果S中的所有字符都是大些,那么返回结果就是True;则,就返回False 36 37 print("_".join(('hello','kugou!'))) #S.join(iterable) -> str #将序列中的元素以指定的字符连接生成一个新的字符串。 38 print(str1.ljust(50,"*")) #S.ljust(width[, fillchar]) -> str 一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。 39 print(str1.lower()) #S.lower() -> str 40 print(str1.lstrip()) #S.lstrip([chars]) -> str 用于截掉字符串左边的空格或指定字符。 41 print(str1.partition('\t')) #S.partition(sep) -> (head, sep, tail) 据指定的分隔符将字符串进行分割。 42 print(str1.replace('he','He',1)) #S.replace(old, new[, count]) -> str 43 44 45 print(str1.rfind('he')) #S.rfind(sub[, start[, end]]) -> int 46 print(str1.rindex('he')) #S.rindex(sub[, start[, end]]) -> int 47 print(str1.rjust(50,'*')) #S.rjust(width[, fillchar]) -> str 48 print("www.kugou.com".rpartition('.')) #S.rpartition(sep) -> (head, sep, tail) 49 print("www.kugou.com".partition('.')) 50 51 print('www.kugou.com'.split('.')) #S.split(sep=None, maxsplit=-1) -> list of strings 通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。 52 print('www.kugou.com'.split('.',1)) #S.split(sep=None, maxsplit=-1) -> list of strings 53 print('www.kugou.com'.rsplit('.')) #S.rsplit(sep=None, maxsplit=-1) -> list of strings 54 print('www.kugou.com'.rsplit('.',1)) #S.rsplit(sep=None, maxsplit=-1) -> list of strings 55 56 57 print(" hello kugou ".strip()) #S.strip([chars]) -> str 58 print("abchello kugouabc".strip('abc')) #S.strip([chars]) -> str 59 print(" hello kugou ".rstrip()) #S.rstrip([chars]) -> str 60 61 62 print("hello kugou\nhello kugou".splitlines()) #S.splitlines([keepends]) -> list of strings 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。 63 print("hello kugou\nhello kugou".splitlines(True)) 64 65 print("hello kugou".startswith("he")) #S.startswith(prefix[, start[, end]]) -> bool 66 print("hello kugou".startswith("ku",6,)) 67 68 69 print("Hello Kugou".swapcase()) # S.swapcase() -> str 方法用于对字符串的大小写字母进行转换。 70 71 72 print("hello kugou".title()) #S.title() -> str 返回"标题化"的字符串,就是说所有单词都是以大写开始 73 74 print("Hello Kugou".upper()) #S.upper() -> str 75 76 77 print("hello kugou".zfill(20)) #S.zfill(width) -> str 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
字符串用法举例:
1 #!/usr/bin/env python 2 3 ''' 4 python 字符串技巧 5 ''' 6 #示例一:找出字符串中最长的单词 7 text1='Hi Everyone your work is going to fill a large part of your life.And the only way to be truly satisfied is to do what you believe is great work in United Nations' 8 text2 = text1.split(" ") 9 text3 = (sorted(text2,key=lambda y:len(y),reverse=True)) 10 print(text3[0]) 11 12 ''' 13 sorted()用法: 14 sorted(iterable, cmp=None, key=None, reverse=False) 15 iterable -- 可迭代对象。 16 key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。 17 reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。 18 ''' 19 li1 = [('a',1),('d',4),('b',2),('c',3)] 20 print(sorted(li1,key=lambda x:x[1])) 21 print(sorted(li1,key=lambda x:x[1],reverse=True,)) 22 23 #示例二:做出长度为5或者6的单词 24 25 #方法一: 26 print([x for x in text2 if len(x) == 5 or len(x) == 6]) 27 28 #方法二: 29 func=lambda x:5 <=len(x) <= 6 30 list1 = list(filter(func,text2)) 31 print(list1) 32 33 ''' 34 filter(function, iterable) 用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。 35 li = [1,2,3,4,5,6,] 36 li1 = list(filter(lambda x:x % 2 == 0,li)) 37 ''' 38 39 #方法三 40 def comp(x): 41 if 5 <= len(x) <= 6: 42 return x 43 print([x for x in map(comp,text2) if x ]) 44 ''' 45 map(func, *iterables) --> map object 46 li = [1,2,3,4,5,6,] 47 map(lambda x:x**2,li) 48 ''' 49 50 #示例三:列出首字母是大写单词 51 52 print([x for x in text2 if x.istitle() ]) 53 import re 54 print([x for x in text2 if re.search('^[A-Z]',x)]) 55 56 #示例四:统计出现频率前三的单次 57 from collections import Counter 58 print(Counter(text2).most_common()) 59 print(Counter(text2).most_common(3)) 60 61 #示例五:字符串拼接 62 names=['Hello',' James',',',' how',' are',' you', '!'] 63 #方法一: 64 s="" 65 for var in names: 66 s+=var 67 print(s) 68 69 #方法二: 70 print("".join(names)) #join的效率比+要高很多 71 72 names2=['Hello',123,'James'] #多种数据类型的列表 73 print(" ".join(map(str,names2)))
3.list(列表)
1 #!/usr/bin/env python 2 3 print(dir(list)) 4 5 li1 = ['hello','world','hello','python'] 6 li2 = list(("aaa",111,"bbb",222,"ccc",333)) 7 8 print(type(li1)) 9 print(type(li2)) 10 11 li1.append('hello') #L.append(object) -> None append object to end 12 li1.append(li2) 13 print(li1) 14 15 #li1.clear() #L.clear() -> None -- remove all items from L 16 print(li1) 17 18 li3 = li2.copy() #L.copy() -> list -- a shallow copy of L 19 print(li3) 20 21 num = li1.count('hello') #L.count(value) -> integer -- return number of occurrences of value 22 print(num) 23 24 li2.extend(li3) #L.extend(iterable) -> None -- extend list by appending elements from the iterable 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。 25 print(li2) 26 27 print(li1.index('hello')) #L.index(value, [start, [stop]]) -> integer -- return first index of value. 28 print(li1.index('hello',1,3)) 29 30 li2.insert(2,'AAA') #L.insert(index, object) -- insert object before index 31 print(li2) 32 33 print(li2.pop()) #L.pop([index]) -> item -- remove and return item at index (default last). 34 print(li2) 35 36 print(li2.pop(3)) 37 print(li2) 38 39 li2.remove('aaa') #L.remove(value) -> None -- remove first occurrence of value. 40 41 print(li2.reverse()) #L.reverse() -- reverse *IN PLACE* 42 print(li2) 43 li1.pop() 44 li1.sort() #L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* 45 print(li1)
4.tuple(元组)
1 #!/usr/bin/env python 2 3 print(dir(tuple)) 4 5 tup1 = ('hello','world','hello','python') 6 tup2 = tuple(('111','aaa','222','bbb','333')) 7 8 print(tup1) 9 print(tup2) 10 print(tup1.count('hello')) #T.count(value) -> integer -- return number of occurrences of value 11 print(tup1.index('hello',1,-1)) #T.index(value, [start, [stop]]) -> integer -- return first index of value.
5.set(集合)
1 #!/usr/bin/env python 2 3 print(dir(set)) 4 set1 = set(("hello","world","hello","python")) 5 set2 = set(['aaa',111,'111','aaa','bbb',222]) 6 print(set1) 7 print(set2) 8 9 set1.add('nihao') #Add an element to a set. 10 #set1.clear() #Remove all elements from this set. 11 set3 = set2.copy() #Return a shallow copy of a set. 12 print(set3) 13 14 x = {"apple",'cherry','bnana'} 15 y = {"pear","orange",'apple'} 16 print(x.difference(y)) #Return the difference of two or more sets as a new set. 返回一个集合,元素包含在集合 x ,但不在集合 y 17 x.difference_update(y) #方法用于移除两个集合中都存在的元素。difference_update() 方法与 difference() 方法的区别在于 difference() 方法返回一个移除相同元素的新集合,而 difference_update() 方法是直接在原来的集合中移除元素,没有返回值。 18 print(x) 19 20 set1.discard('hello') #Remove an element from a set if it is a member.If the element is not a member, do nothing. 21 print(set1) 22 23 x = {"apple",'cherry','bnana'} 24 y = {"pear","orange",'apple'} 25 z = x.intersection(y) #Return the intersection of two sets as a new set.i.e. all elements that are in both sets.) 集合交集 26 print(z) 27 x.intersection_update(y) #Update a set with the intersection of itself and another. intersection_update() 方法用于获取两个或更多集合中都重叠的元素,即计算交集,intersection_update() 方法不同于 intersection() 方法,因为 intersection() 方法是返回一个新的集合,而 intersection_update() 方法是在原始的集合上移除不重叠的元素 28 print(x) 29 30 print(x.isdisjoint(y)) #Return True if two sets have a null intersection. 用于判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 31 print(x.issubset(y)) #Report whether another set contains this set. 用于判断集合的所有元素是否都包含在指定集合中,如果是则返回 True,否则返回 False. 32 print(y.issuperset(x)) #Report whether this set contains another set. 用于判断指定集合的所有元素是否都包含在原始的集合中,如果是则返回 True,否则返回 False。 33 34 print(set2.pop()) #Remove and return an arbitrary set element.Raises KeyError if the set is empty. 35 36 set2.remove('111') #Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. 37 print(set2) 38 39 40 x = {"apple",'cherry','bnana'} 41 y = {"pear","orange",'apple'} 42 43 z = x.symmetric_difference(y) #Return the symmetric difference of two sets as a new set. 返回两个集合中不重复的元素集合,即会移除两个集合中都存在的元素。 44 print(z) 45 46 x.symmetric_difference_update(y) #symmetric_difference_update() 方法移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中 47 print(x) 48 49 x = {"apple",'cherry','bnana'} 50 y = {"pear","orange",'apple'} 51 z = x.union(y) #Return the union of sets as a new set. 方法返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次。 52 x.update(y) #用于修改当前集合,可以添加新的元素或集合到当前集合中,如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。 53 print(x)
6.dict(字典)
1 #!/usr/bin/env python 2 3 print(dir(dict)) 4 5 dict1 = { 6 'name':'nuannuan', 7 'age':3, 8 'addr':'广东广州', 9 'favi':'画画,跳舞', 10 } 11 12 print(dict1) 13 #dict1.clear() #D.clear() -> None. Remove all items from D. 14 #print(dict1) 15 16 dict2 = dict1.copy() #D.copy() -> a shallow copy of D 17 print(dict2) 18 19 seq = ('a','b','c') 20 dict3 = {}.fromkeys(seq,"xxxx") #Returns a new dict with keys from iterable and values equal to value. 创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值。 21 print(dict3) 22 23 print(dict1.get('name')) #D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. 24 print(dict1.get('skill','singing')) 25 26 print(dict1.items()) #D.items() -> a set-like object providing a view on D's items 27 for k,v in dict1.items(): 28 print(k,v) 29 30 print(dict1.keys()) #D.keys() -> a set-like object providing a view on D's keys 31 for k in dict1.keys(): 32 print(k,dict1[k]) 33 34 print(dict1.pop('name','xxx')) #D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised 35 print(dict1) 36 print(dict1.pop('skill','singing')) 37 38 print(dict1.popitem()) # D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. 39 print(dict1) 40 41 42 print(dict1.setdefault('addr','xxx')) #setdefault() 函数和 get()方法 类似, 如果键不存在于字典中,将会添加键并将值设为默认值。 43 print(dict1) 44 print(dict1.setdefault('skill','singing')) 45 print(dict1) 46 47 dict2 = { 48 'aaa':111, 49 'bbb':222, 50 } 51 dict3 = { 52 'ccc':333, 53 'ddd':333, 54 } 55 dict4 = { 56 'bbb':444, 57 'ddd':555, 58 } 59 dict2.update(dict3) #把字典dict2的键/值对更新到dict里。 60 print(dict2) 61 dict2.update(dict4) #有相同的键会直接替换成 update 的值: 62 print(dict2) 63 64 print(dict1.values()) #D.values() -> an object providing a view on D's values
浙公网安备 33010602011771号