基本数据类型

bytes数据类型

Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes,正是这使得两者的区分特别清晰。你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然)。这是件好事。

不管怎样,字符串和字节包之间的界线是必然的,下面的图解非常重要,务请牢记于心:

字符串可以编码成字节包,而字节包可以解码成字符串。

>>>'€20'.encode('utf-8')
b'\xe2\x82\xac20'
>>> b'\xe2\x82\xac20'.decode('utf-8')
'€20'

数字

2是一个整数的例子。

长整数 不过是大一些的整数。

3.23和52.3E-4是浮点数的例子,E标记表示10的幂。在这里,52.3E-4表示52.3*10-4.

(-5+4j)和(2.3-4.6j)是复数的例子,其中-5,4为实数,j为虚数,数学中表示复数是什么?。

int(整型)

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

class int(object):"""int(x=0) -> int or longint(x, base=10) -> int or longConvert a number or string to an integer, or return 0 if no argumentsare given.  If x is floating point, the conversion truncates towards zero.If x is outside the integer range, the function returns a long instead.If x is not a number or if base is given, then x must be a string orUnicode object representing an integer literal in the given base.  Theliteral can be preceded by '+' or '-' and be surrounded by whitespace.The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means tointerpret the base from the string as an integer literal.>>> int('0b100', base=0)"""def bit_length(self): """ 返回表示该数字的时占用的最少位数 """"""int.bit_length() -> intNumber of bits necessary to represent self in binary.>>> bin(37)'0b100101'>>> (37).bit_length()"""return 0def conjugate(self, *args, **kwargs): # real signature unknown""" 返回该复数的共轭复数 """""" Returns self, the complex conjugate of any int. """passdef __abs__(self):""" 返回绝对值 """""" x.__abs__() <==> abs(x) """passdef __add__(self, y):""" x.__add__(y) <==> x+y """passdef __and__(self, y):""" x.__and__(y) <==> x&y """passdef __cmp__(self, y): """ 比较两个数大小 """""" x.__cmp__(y) <==> cmp(x,y) """passdef __coerce__(self, y):""" 强制生成一个元组 """ """ x.__coerce__(y) <==> coerce(x, y) """passdef __divmod__(self, y): """ 相除,得到商和余数组成的元组 """ """ x.__divmod__(y) <==> divmod(x, y) """passdef __div__(self, y): """ x.__div__(y) <==> x/y """passdef __float__(self): """ 转换为浮点类型 """ """ x.__float__() <==> float(x) """passdef __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """passdef __format__(self, *args, **kwargs): # real signature unknownpassdef __getattribute__(self, name): """ x.__getattribute__('name') <==> x.name """passdef __getnewargs__(self, *args, **kwargs): # real signature unknown""" 内部调用 __new__方法或创建对象时传入参数使用 """ passdef __hash__(self): """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""""" x.__hash__() <==> hash(x) """passdef __hex__(self): """ 返回当前数的 十六进制 表示 """ """ x.__hex__() <==> hex(x) """passdef __index__(self): """ 用于切片,数字无意义 """""" x[y:z] <==> x[y.__index__():z.__index__()] """passdef __init__(self, x, base=10): # known special case of int.__init__""" 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """ """int(x=0) -> int or longint(x, base=10) -> int or longConvert a number or string to an integer, or return 0 if no argumentsare given.  If x is floating point, the conversion truncates towards zero.If x is outside the integer range, the function returns a long instead.If x is not a number or if base is given, then x must be a string orUnicode object representing an integer literal in the given base.  Theliteral can be preceded by '+' or '-' and be surrounded by whitespace.The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means tointerpret the base from the string as an integer literal.>>> int('0b100', base=0)# (copied from class doc)"""passdef __int__(self): """ 转换为整数 """ """ x.__int__() <==> int(x) """passdef __invert__(self): """ x.__invert__() <==> ~x """passdef __long__(self): """ 转换为长整数 """ """ x.__long__() <==> long(x) """passdef __lshift__(self, y): """ x.__lshift__(y) <==> x<<y """passdef __mod__(self, y): """ x.__mod__(y) <==> x%y """passdef __mul__(self, y): """ x.__mul__(y) <==> x*y """passdef __neg__(self): """ x.__neg__() <==> -x """pass@staticmethod # known case of __new__def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __nonzero__(self): """ x.__nonzero__() <==> x != 0 """passdef __oct__(self): """ 返回改值的 八进制 表示 """ """ x.__oct__() <==> oct(x) """passdef __or__(self, y): """ x.__or__(y) <==> x|y """passdef __pos__(self): """ x.__pos__() <==> +x """passdef __pow__(self, y, z=None): """ 幂,次方 """ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """passdef __radd__(self, y): """ x.__radd__(y) <==> y+x """passdef __rand__(self, y): """ x.__rand__(y) <==> y&x """passdef __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """passdef __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """passdef __repr__(self): """转化为解释器可读取的形式 """""" x.__repr__() <==> repr(x) """passdef __str__(self): """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""""" x.__str__() <==> str(x) """passdef __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """passdef __rlshift__(self, y): """ x.__rlshift__(y) <==> y<<x """passdef __rmod__(self, y): """ x.__rmod__(y) <==> y%x """passdef __rmul__(self, y): """ x.__rmul__(y) <==> y*x """passdef __ror__(self, y): """ x.__ror__(y) <==> y|x """passdef __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """passdef __rrshift__(self, y): """ x.__rrshift__(y) <==> y>>x """passdef __rshift__(self, y): """ x.__rshift__(y) <==> x>>y """passdef __rsub__(self, y): """ x.__rsub__(y) <==> y-x """passdef __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """passdef __rxor__(self, y): """ x.__rxor__(y) <==> y^x """passdef __sub__(self, y): """ x.__sub__(y) <==> x-y """passdef __truediv__(self, y): """ x.__truediv__(y) <==> x/y """passdef __trunc__(self, *args, **kwargs): """ 返回数值被截取为整形的值,在整形中无意义 """passdef __xor__(self, y): """ x.__xor__(y) <==> x^y """passdenominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default""" 分母 = 1 """"""the denominator of a rational number in lowest terms"""imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default""" 虚数,无意义 """"""the imaginary part of a complex number"""numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default""" 分子 = 数字大小 """"""the numerator of a rational number in lowest terms"""real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default""" 实属,无意义 """"""the real part of a complex number"""int

int

long(长整型)

  跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。

  注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。

float (浮点型)

  浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。

complex(复数)

  复数由实数部分和虚数部分组成,一般形式为x + yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。

  注:Python中存在小数池-5~257

布尔值

布尔值在Python中如何定义呢?

>>>True
True
>>>False
False#注意!都是大写

真或假

1或0

>>>0 == True
False
>>>0 == False
True#由此可见0代表False,而1代表True

字符串

"Hello world"

万恶的字符串拼接:

  python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内存中重新开辟一块空间像下面这样,所以我们要尽量避免这样的情况发生:

>>>name = 'bourbon'#开辟了3快内存空间,需要去内存里找3次,把数据拼出来
>>>print("my name is " + name + "and you ?") #输出
my name is bourbon and you ?

字符串格式化

>>>name='bourbon'
>>>print "i am %s" %name#输出
i am bourbon

PS:字符串是%s;整数%d;浮点数%f

 1 name = input("input your name:")
 2 age = int(input("input your age:"))
 3 job = input("input your job:")
 4
 5 msg = '''
 6 information of user %s:
 7 ----------------------
 8 name:   %s
 9 age :   %d
10 job :   %s
11 --------End-----------
12 ''' % (name,name,age,job )
13 print(msg)

View Code

字符串功能:

· 移除空白

username = input("input your name:")
if username.strip() == "bourbon":print("welcome")#strip() 移除首尾的空白

· 分割

>>>name = "bourbon,jacky,lio"
>>>name2 = name.split(",")
>>>print(name2)
#按照","进行拆分,将字符串拆成一个列表
['bourbon', 'jacky', 'lio']  >>>name = "bourbon,jacky,lio"
>>>name2 = name.split(",")
>>>print("|".join(name2))
#按照"|"将列表里的每一个元素重新合成一个新的字符串
bourbon|jacky|lio

· 长度

· 索引

· 切片

name = "Bourbon Tian"
print(name[2:4])# 输出
ur

name = "sheldon"# 以什么结尾
print(name.endswith("on"))  # 以什么开头
print(name.startswith("on"))  # 全大写
print(name.upper())# 全小写
print(name.lower())  # 输出
True
False
SHELDON
sheldon

>>>name = "bourbon tian"
>>>print(name.center(40,'-'))
--------------bourbon tian--------------

class str(basestring):"""str(object='') -> stringReturn a nice string representation of the object.If the argument is a string, the return value is the same object."""def capitalize(self):  """ 首字母变大写 """"""S.capitalize() -> stringReturn a copy of the string S with only its first charactercapitalized."""return ""def center(self, width, fillchar=None):  """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """"""S.center(width[, fillchar]) -> stringReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def count(self, sub, start=None, end=None):  """ 子序列个数 """"""S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end].  Optional arguments start and end are interpretedas in slice notation."""return 0def decode(self, encoding=None, errors=None):  """ 解码 """"""S.decode([encoding[,errors]]) -> objectDecodes S using the codec registered for encoding. encoding defaultsto the default encoding. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeDecodeError. Other possible values are 'ignore' and 'replace'as well as any other name registered with codecs.register_error that isable to handle UnicodeDecodeErrors."""return object()def encode(self, encoding=None, errors=None):  """ 编码,针对unicode """"""S.encode([encoding[,errors]]) -> objectEncodes S using the codec registered for encoding. encoding defaultsto the default encoding. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that is able to handle UnicodeEncodeErrors."""return object()def endswith(self, suffix, start=None, end=None):  """ 是否以 xxx 结束 """"""S.endswith(suffix[, start[, end]]) -> boolReturn True if S ends with the specified suffix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try."""return Falsedef expandtabs(self, tabsize=None):  """ 将tab转换成空格,默认一个tab转换成8个空格 """"""S.expandtabs([tabsize]) -> stringReturn a copy of S where all tab characters are expanded using spaces.If tabsize is not given, a tab size of 8 characters is assumed."""return ""def find(self, sub, start=None, end=None):  """ 寻找子序列位置,如果没找到,返回 -1 """"""S.find(sub [,start [,end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end].  Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def format(*args, **kwargs): # known special case of str.format""" 字符串格式化,动态参数,将函数式编程时细说 """"""S.format(*args, **kwargs) -> stringReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""passdef index(self, sub, start=None, end=None):  """ 子序列位置,如果没找到,报错 """S.index(sub [,start [,end]]) -> intLike S.find() but raise ValueError when the substring is not found."""return 0def isalnum(self):  """ 是否是字母和数字 """"""S.isalnum() -> boolReturn True if all characters in S are alphanumericand there is at least one character in S, False otherwise."""return Falsedef isalpha(self):  """ 是否是字母 """"""S.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return Falsedef isdigit(self):  """ 是否是数字 """"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return Falsedef islower(self):  """ 是否小写 """"""S.islower() -> boolReturn True if all cased characters in S are lowercase and there isat least one cased character in S, False otherwise."""return Falsedef isspace(self):  """S.isspace() -> boolReturn True if all characters in S are whitespaceand there is at least one character in S, False otherwise."""return Falsedef istitle(self):  """S.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. uppercase characters may only follow uncasedcharacters and lowercase characters only cased ones. Return Falseotherwise."""return Falsedef isupper(self):  """S.isupper() -> boolReturn True if all cased characters in S are uppercase and there isat least one cased character in S, False otherwise."""return Falsedef join(self, iterable):  """ 连接 """"""S.join(iterable) -> stringReturn a string which is the concatenation of the strings in theiterable.  The separator between elements is S."""return ""def ljust(self, width, fillchar=None):  """ 内容左对齐,右侧填充 """"""S.ljust(width[, fillchar]) -> stringReturn S left-justified in a string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def lower(self):  """ 变小写 """"""S.lower() -> stringReturn a copy of the string S converted to lowercase."""return ""def lstrip(self, chars=None):  """ 移除左侧空白 """"""S.lstrip([chars]) -> string or unicodeReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def partition(self, sep):  """ 分割,前,中,后三部分 """"""S.partition(sep) -> (head, sep, tail)Search for the separator sep in S, and return the part before it,the separator itself, and the part after it.  If the separator is notfound, return S and two empty strings."""passdef replace(self, old, new, count=None):  """ 替换 """"""S.replace(old, new[, count]) -> stringReturn a copy of string S with all occurrences of substringold replaced by new.  If the optional argument count isgiven, only the first count occurrences are replaced."""return ""def rfind(self, sub, start=None, end=None):  """S.rfind(sub [,start [,end]]) -> intReturn the highest index in S where substring sub is found,such that sub is contained within S[start:end].  Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def rindex(self, sub, start=None, end=None):  """S.rindex(sub [,start [,end]]) -> intLike S.rfind() but raise ValueError when the substring is not found."""return 0def rjust(self, width, fillchar=None):  """S.rjust(width[, fillchar]) -> stringReturn S right-justified in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def rpartition(self, sep):  """S.rpartition(sep) -> (head, sep, tail)Search for the separator sep in S, starting at the end of S, and returnthe part before it, the separator itself, and the part after it.  If theseparator is not found, return two empty strings and S."""passdef rsplit(self, sep=None, maxsplit=None):  """S.rsplit([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string, starting at the end of the string and workingto the front.  If maxsplit is given, at most maxsplit splits aredone. If sep is not specified or is None, any whitespace stringis a separator."""return []def rstrip(self, chars=None):  """S.rstrip([chars]) -> string or unicodeReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def split(self, sep=None, maxsplit=None):  """ 分割, maxsplit最多分割几次 """"""S.split([sep [,maxsplit]]) -> list of stringsReturn a list of the words in the string S, using sep as thedelimiter string.  If maxsplit is given, at most maxsplitsplits are done. If sep is not specified or is None, anywhitespace string is a separator and empty strings are removedfrom the result."""return []def splitlines(self, keepends=False):  """ 根据换行分割 """"""S.splitlines(keepends=False) -> list of stringsReturn a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keependsis given and true."""return []def startswith(self, prefix, start=None, end=None):  """ 是否起始 """"""S.startswith(prefix[, start[, end]]) -> boolReturn 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 Falsedef strip(self, chars=None):  """ 移除两段空白 """"""S.strip([chars]) -> string or unicodeReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead.If chars is unicode, S will be converted to unicode before stripping"""return ""def swapcase(self):  """ 大写变小写,小写变大写 """"""S.swapcase() -> stringReturn a copy of the string S with uppercase charactersconverted to lowercase and vice versa."""return ""def title(self):  """S.title() -> stringReturn a titlecased version of S, i.e. words start with uppercasecharacters, all remaining cased characters have lowercase."""return ""def translate(self, table, deletechars=None):  """转换,需要先做一个对应表,最后一个表示删除字符集合intab = "aeiou"outtab = "12345"trantab = maketrans(intab, outtab)str = "this is string example....wow!!!"print str.translate(trantab, 'xm')""""""S.translate(table [,deletechars]) -> stringReturn a copy of the string S, where all characters occurringin the optional argument deletechars are removed, and theremaining characters have been mapped through the giventranslation table, which must be a string of length 256 or None.If the table argument is None, no translation is applied andthe operation simply removes the characters in deletechars."""return ""def upper(self):  """S.upper() -> stringReturn a copy of the string S converted to uppercase."""return ""def zfill(self, width):  """方法返回指定长度的字符串,原字符串右对齐,前面填充0。""""""S.zfill(width) -> stringPad a numeric string S with zeros on the left, to fill a fieldof the specified width.  The string S is never truncated."""return ""def _formatter_field_name_split(self, *args, **kwargs): # real signature unknownpassdef _formatter_parser(self, *args, **kwargs): # real signature unknownpassdef __add__(self, y):  """ x.__add__(y) <==> x+y """passdef __contains__(self, y):  """ x.__contains__(y) <==> y in x """passdef __eq__(self, y):  """ x.__eq__(y) <==> x==y """passdef __format__(self, format_spec):  """S.__format__(format_spec) -> stringReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, name):  """ x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y):  """ x.__getitem__(y) <==> x[y] """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __getslice__(self, i, j):  """x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y):  """ x.__ge__(y) <==> x>=y """passdef __gt__(self, y):  """ x.__gt__(y) <==> x>y """passdef __hash__(self):  """ x.__hash__() <==> hash(x) """passdef __init__(self, string=''): # known special case of str.__init__"""str(object='') -> stringReturn a nice string representation of the object.If the argument is a string, the return value is the same object.# (copied from class doc)"""passdef __len__(self):  """ x.__len__() <==> len(x) """passdef __le__(self, y):  """ x.__le__(y) <==> x<=y """passdef __lt__(self, y):  """ x.__lt__(y) <==> x<y """passdef __mod__(self, y):  """ x.__mod__(y) <==> x%y """passdef __mul__(self, n):  """ x.__mul__(n) <==> x*n """pass@staticmethod # known case of __new__def __new__(S, *more):  """ T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y):  """ x.__ne__(y) <==> x!=y """passdef __repr__(self):  """ x.__repr__() <==> repr(x) """passdef __rmod__(self, y):  """ x.__rmod__(y) <==> y%x """passdef __rmul__(self, n):  """ x.__rmul__(n) <==> n*x """passdef __sizeof__(self):  """ S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self):  """ x.__str__() <==> str(x) """pass

str

列表

创建列表:

>>>age = 9
>>>name = ["jack","jerry","jason",22,age]
>>>print(name)
['jack','jerry','jason',22,9]

列表都是"[]"号开始,通过","隔开,字符串是元素,元素也可以是数字、变量。

基本操作:

· 索引

第一个索引是0,第二个索引是1,以此类推。

>>>name[0]
'jack'
>>>name[1]
'jerry'
>>>name[-1]
9
>>>name[-2]
22

· 切片

>>>name[0:2]
#虎头蛇尾,永远不包含最后一个
['jack','jerry']
>>>name[0:2][0]
'jack'
>>>name[0:2][0][1]
'a'

PS:只能正着取值

· 更改插入追加

#更改
>>>name[1] = "bourbon"
>>>name
['jack','bourbon','jason',22,9]#插入
>>>name.insert(2,'lio')
>>>name
['jack','bourbon','lio','jason',22,9]#追加
>>>name.append("eric")
>>>name
['jack','bourbon','lio','jason',22,9,'eric']

· 删除

>>>name.remove("lio")
>>>name
['jack','bourbon','jason',22,9,'eric']>>>del name[1]
>>>name
['jack','jason',22,9,'eric']#name.pop(“这里输入下标”) ,默认删除最后一个下标。
>>>name.pop()
'eric'
>>>name
['jack','jason',22,9]

· 长度

· 循环

· 包含

扩展表
>>>name = [32,23,21,52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>name2 = [453,5435,76575,2132]
>>>name.extend(name2)
>>>print(name)
[32, 23, 21, 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9, 453, 5435, 76575, 2132]反转表
>>>name = [32,23,21,52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>name.reverse()
>>>print(name)
[9, 9, 4335, 2134, 5435, 98, 76, 68, 7, 546, 14, 52, 21, 23, 32]排序表
>>>name = [32,23,21,52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>name.sort()
>>>print (name)
[7, 9, 9, 14, 21, 23, 32, 52, 68, 76, 98, 546, 2134, 4335, 5435]清空表
>>>name.clear()
>>>print(name)
[]拷贝表
>>>name = [32,23,21,52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>name3 = name.copy()
>>>name[0] = "Alex"
>>>print(name3)
>>>print(name)
[32, 23, 21, 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9]#PS:python 默认只copy第一层,因为copy的内存地址>>>name = [32,23,21,[1321,124314,45654,342],52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>name3 = name.copy()
>>>name[0] = "Bourbon"
>>>name[3][0] = 11111
>>>print(name3)
>>>print(name)
[32, 23, 21, [11111, 124314, 45654, 342], 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9]
['Bourbon', 23, 21, [11111, 124314, 45654, 342], 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9]>>>print(id(name[3]),id(name3[3]))
8632520 8632520PS:深度copy的方式
>>>import copy
>>>name = [32,23,21,[1321,124314,45654,342],52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>name3 = name.copy()
>>>name4 = copy.deepcopy(name) #深度copy
>>>name[0] = "Bourbon"
>>>name[3][0] = 11111
>>>print(name3)
>>>print(name)
>>>print(name4)
[32, 23, 21, [11111, 124314, 45654, 342], 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9]
['Bourbon', 23, 21, [11111, 124314, 45654, 342], 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9]
[32, 23, 21, [1321, 124314, 45654, 342], 52, 14, 546, 7, 68, 76, 98, 5435, 2134, 4335, 9, 9]>>>print(id(name[3]),id(name4[3]))
7781128 7780232显示列表的长度
>>>name = [32,23,21,[1321,124314,45654,342],52,14,546,7,68,76,98,5435,2134,4335,9,9]
>>>print(len(name))
16

list

· 查询

a = ['jerry','jacky','jason','bourbon']
print(a.index("jason"))# 输出
2

· 枚举

#枚举函数,打印下表:
a = ['jarry','jacky','bouron']
for index,i in enumerate(a):print(index,i)#输出
0 jerry
1 jacky
2 bouron

元组(不可变列表)

创建元组:

ages = (11,22,33,44,55)或ages = tuple((11,22,33,44,55))

基本操作:

· 索引

· 切片

· 循环

· 长度

· 包含

lass tuple(object):"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object."""def count(self, value): # real signature unknown; restored from __doc__""" T.count(value) -> integer -- return number of occurrences of value """return 0def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__"""T.index(value, [start, [stop]]) -> integer -- return first index of value.Raises ValueError if the value is not present."""return 0def __add__(self, y): # real signature unknown; restored from __doc__""" x.__add__(y) <==> x+y """passdef __contains__(self, y): # real signature unknown; restored from __doc__""" x.__contains__(y) <==> y in x """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __getslice__(self, i, j): # real signature unknown; restored from __doc__"""x.__getslice__(i, j) <==> x[i:j]Use of negative indices is not supported."""passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __hash__(self): # real signature unknown; restored from __doc__""" x.__hash__() <==> hash(x) """passdef __init__(self, seq=()): # known special case of tuple.__init__"""tuple() -> empty tupletuple(iterable) -> tuple initialized from iterable's itemsIf the argument is a tuple, the return value is the same object.# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """passdef __mul__(self, n): # real signature unknown; restored from __doc__""" x.__mul__(n) <==> x*n """pass@staticmethod # known case of __new__def __new__(S, *more): # real signature unknown; restored from __doc__""" T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __rmul__(self, n): # real signature unknown; restored from __doc__""" x.__rmul__(n) <==> n*x """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" T.__sizeof__() -- size of T in memory, in bytes """passtuple

tuple

字典(无序)

创建字典:

id_db = {1234567890:{'name':"Tian si han",'age':22,'addr':'changzhou'},9876543210:{'name':'Tian si nuan','age':'23','addr':'changzhou'}}
print(id_db)#输出
{1234567890: {'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'}, 9876543210: {'age': '23', 'addr': 'changzhou', 'name': 'Tian si nuan'}}

常用操作:

· 索引

# 查找 (最安全的获取方法)
print(id_db[1234567890].get('name'))# 输出
Tian si hanprint(id_db[1234567890].get('job'))# 输出
None

· 新增

#添加元素
id_db[1234567890]['qq_num'] = 75298335
print(id_db[1234567890])#输出
{'addr': 'changzhou', 'qq_num': 75298335, 'name': 'Tian si han', 'age': 22}

· 删除

#删除元素
id_db[9876543210].pop("addr")
print(id_db[9876543210])#输出
{'name': 'Tian si nuan', 'age': '23'}

· 更改

#更改元素
id_db[9876543210]['name'] = "Tian si leng"
print(id_db[9876543210])#输出
{'age': '23', 'name': 'Tian si leng'}

· 键、值、键值对

· 循环

· 长度

class dict(object):"""dict() -> new empty dictionarydict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairsdict(iterable) -> new dictionary initialized as if via:d = {}for k, v in iterable:d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairsin the keyword argument list.  For example:  dict(one=1, two=2)"""def clear(self): # real signature unknown; restored from __doc__""" 清除内容 """""" D.clear() -> None.  Remove all items from D. """passdef copy(self): # real signature unknown; restored from __doc__""" 浅拷贝 """""" D.copy() -> a shallow copy of D """pass@staticmethod # known casedef fromkeys(S, v=None): # real signature unknown; restored from __doc__"""dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.v defaults to None."""passdef get(self, k, d=None): # real signature unknown; restored from __doc__""" 根据key获取值,d是默认值 """""" D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """passdef has_key(self, k): # real signature unknown; restored from __doc__""" 是否有key """""" D.has_key(k) -> True if D has a key k, else False """return Falsedef items(self): # real signature unknown; restored from __doc__""" 所有项的列表形式 """""" D.items() -> list of D's (key, value) pairs, as 2-tuples """return []def iteritems(self): # real signature unknown; restored from __doc__""" 项可迭代 """""" D.iteritems() -> an iterator over the (key, value) items of D """passdef iterkeys(self): # real signature unknown; restored from __doc__""" key可迭代 """""" D.iterkeys() -> an iterator over the keys of D """passdef itervalues(self): # real signature unknown; restored from __doc__""" value可迭代 """""" D.itervalues() -> an iterator over the values of D """passdef keys(self): # real signature unknown; restored from __doc__""" 所有的key列表 """""" D.keys() -> list of D's keys """return []def pop(self, k, d=None): # real signature unknown; restored from __doc__""" 获取并在字典中移除 """"""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"""passdef popitem(self): # real signature unknown; restored from __doc__""" 获取并在字典中移除 """"""D.popitem() -> (k, v), remove and return some (key, value) pair as a2-tuple; but raise KeyError if D is empty."""passdef setdefault(self, k, d=None): # real signature unknown; restored from __doc__""" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """passdef update(self, E=None, **F): # known special case of dict.update""" 更新{'name':'alex', 'age': 18000}[('name','sbsbsb'),]""""""D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.If E present and has a .keys() method, does:     for k in E: D[k] = E[k]If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = vIn either case, this is followed by: for k in F: D[k] = F[k]"""passdef values(self): # real signature unknown; restored from __doc__""" 所有的值 """""" D.values() -> list of D's values """return []def viewitems(self): # real signature unknown; restored from __doc__""" 所有项,只是将内容保存至view对象中 """""" D.viewitems() -> a set-like object providing a view on D's items """passdef viewkeys(self): # real signature unknown; restored from __doc__""" D.viewkeys() -> a set-like object providing a view on D's keys """passdef viewvalues(self): # real signature unknown; restored from __doc__""" D.viewvalues() -> an object providing a view on D's values """passdef __cmp__(self, y): # real signature unknown; restored from __doc__""" x.__cmp__(y) <==> cmp(x,y) """passdef __contains__(self, k): # real signature unknown; restored from __doc__""" D.__contains__(k) -> True if D has a key k, else False """return Falsedef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <==> del x[y] """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __init__(self, seq=None, **kwargs): # known special case of dict.__init__"""dict() -> new empty dictionarydict(mapping) -> new dictionary initialized from a mapping object's(key, value) pairsdict(iterable) -> new dictionary initialized as if via:d = {}for k, v in iterable:d[k] = vdict(**kwargs) -> new dictionary initialized with the name=value pairsin the keyword argument list.  For example:  dict(one=1, two=2)# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """pass@staticmethod # known case of __new__def __new__(S, *more): # real signature unknown; restored from __doc__""" T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __setitem__(self, i, y): # real signature unknown; restored from __doc__""" x.__setitem__(i, y) <==> x[i]=y """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" D.__sizeof__() -> size of D in memory, in bytes """pass__hash__ = Nonedict

dict

PS:循环,range,continue和break

#把字典变成一个元组(列表)    一般不用
print(id_db.items())#输出
dict_items([(1234567890, {'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'}), (9876543210, {'age': '23', 'addr': 'changzhou', 'name': 'Tian si nuan'})])#------------------------------------------------------------------------------------------------#打印字典里所有的vlave        一般不用
print(id_db.values())#输出
dict_values([{'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'}, {'age': '23', 'addr': 'changzhou', 'name': 'Tian si nuan'}])#-----------------------------------------------------------------------------------------------#打印字典里所有的key值
print(id_db.keys())                      #输出
dict_keys([1234567890, 9876543210])#-----------------------------------------------------------------------------------------------
#取一个key,如果存在就输出这个key的值
print(id_db.setdefault(1234567890))            #输出
{'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'}#----------------------------------------------------------------------------------------------#取一个key,如果不存在就设置一个key的值    输出:hahah
print(id_db.setdefault(1345678902,"hahah"))         #输出
hahah#----------------------------------------------------------------------------------------------#随机删除    一般不用
print(id_db.popitem())#输出
(1234567890, {'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'})#----------------------------------------------------------------------------------------------#高效循环
for key in id_db:                           print(key,id_db[key])#输出
1234567890 {'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'}
9876543210 {'age': '23', 'addr': 'changzhou', 'name': 'Tian si nuan'}#----------------------------------------------------------------------------------------------#取值
v = id_db.get(1234567890)
print(v)#输出
{'age': 22, 'addr': 'changzhou', 'name': 'Tian si han'}y = id_db.get(111111111)
print(y)#输出
None#-------------------------------------------------------------------------------------------
dic2 = {'name':"bourbon",1234567890:{'name':"Tian si han",'age':23,'addr':"changzhou"},
}
id_db.update(dic2)
print(id_db)#输出
{1234567890: {'age': 23, 'addr': 'changzhou', 'name': 'Tian si han'}, 9876543210: {'age': '23', 'addr': 'changzhou', 'name': 'Tian si nuan'}, 'name': 'bourbon'}

转载于:https://www.cnblogs.com/Bourbon-tian/p/5892151.html

Python学习【第七篇】基本数据类型相关推荐

  1. python学习 第七篇 sql优化

    查询单条语句:用来获取用户列表和单个用户 >>> fields=["id","name","name_cn"," ...

  2. 猿编程python代码_程序猿编程课堂 Python学习之入门篇3:简单的数据类型

    1. 什么是数据类型? 我们知道编程就是编写程序解决某个问题,而任何能使用编程来解决的问题都是能够提取或者转换出相应的数据,只是数据的表达形式是不一样的,而这表达形式就是数据类型. 比如,数学中的数字 ...

  3. python学习[第十三篇] 条件和循环

    python学习[第十三篇] 条件和循环 if语句 单一if 语句 if语句有三个部分构成,关键字if本身,判断结果真假的条件表达式,以及表达式为真或非0是执行的代码 if expression: e ...

  4. Python学习第七课-元组字典集合

    Python学习第七课-元组&字典&集合 一.元组 1.1元组简介 1.2元组的拆包 1.3字符串拆包 1.4列表的拆包 1.5拆包练习 二.字典的简介 2.1介绍 2.2操作 三.字 ...

  5. python学习历程-安装篇(一)

    python学习历程-安装篇 之前工作中数据量很少,每天也就是用excel发一下报表,函数已经足够应付工作内容,但心里一直渴望学习更深层次一点的数据分析(崇拜那些技术大神),网上看了很多有关数据分析挖 ...

  6. 程序猿编程课堂 Python学习之入门篇1:环境搭建与第一个程序

    前言: Python作为目前比较热门的编程语言,其简单和简洁的语法使它成为一种非常好的通用编程语言,它是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),并且随着版本的不断更新和 ...

  7. Python学习第三课-基本数据类型

    Python学习第三课-基本数据类型 一.基本概念 1.1表达式 1.2语句 1.3程序 1.4函数 内置函数 自定义函数 参数 返回值 二.标识符 2.1 关键字 2.2标识符概念 驼峰命名法 下划 ...

  8. python学习记录——容器篇

    容器 字符串 下标(索引) # 下表也称为是索引,是一个整型数字,可以是正数,也可以是负数 # 正数下标是从0开始的,表示第一个字符,-1表示最后一个字符 my_str = 'hello'h e l ...

  9. python学习的几篇文章推荐

    作为脚本语言Python上手容易,但要学好Python能写出一手漂亮的.Pythonic的Python代码并非一日之功,本文的目的在于推荐一些优秀的Python相关的文章(至于书大家可以看dip.le ...

  10. group by rollup 变量名为空值_【Python学习笔记】07、数据类型和变量

    在Python中,能够直接处理的数据类型有以下几种: 整数 Python可以处理任意大小的整数,包括负整数,例如:1,100,-8080,0,等等. 计算机由于使用二进制,所以,有时候用十六进制表示整 ...

最新文章

  1. 思维dp ---- Codeforces Round #722 (Div. 1) B. Kavi on Pairing Duty [思维dp + 数学]
  2. linux下怎么修改mysql的字符集编码
  3. 如何使用SAP APF里的过滤器
  4. HTMLCSS————CSS常用选择器及优先级
  5. python中__init__导入失败_python - 如何使用__init__.py修复“在非包中尝试相对导入”...
  6. 使用DataAnnotations实现数据验证
  7. 部署速度翻6倍,知乎从0到1实现部署系统演进及优化
  8. 使用jQuery+huandlebars遍历中if判断
  9. c语言简单程序设计思维导图,用来梳理c编程核心知识思维导图
  10. 联想微型计算机如果进入BIos,联想怎么进入bios 【处理方法】
  11. 曲线拟合最小二乘法对数c语言实现,基于最小二乘法的曲线拟合
  12. Rxjava + retrofit + dagger2 + mvp搭建Android框架
  13. java 状态模式 同步_多人联机射击游戏中的设计模式应用(二):观察者模式,单例模式,状态模式,适配器模式...
  14. Web全栈开发训练营
  15. js获取随机数与随机颜色函数的简单封装
  16. 重磅 | 向未来致敬!2017网易未来科技峰会乌镇论坛将于12月4日在乌镇举办
  17. html语言全拼,html标签全拼意思是什么
  18. 小程序创业,有哪些行业方向可以选?
  19. 数据交换系统-软件评测知识(分享篇)
  20. 20220310_CSS学习01、Chrome调试工具

热门文章

  1. java-在应用中获取spring定义的bean
  2. 编码和编码格式一样吗?_学习如何像专业人士一样编码
  3. 如何使用Create-React-App和自定义服务人员构建PWA
  4. 服务器部署基础知识_我在生产部署期间学到的知识
  5. 需求简报_代码简报:有史以来最怪诞的丑毛衣
  6. ESXi6.5环境搭建(一:VMware Workstations 12 Pro 环境的安装及配置)
  7. 海思涵科技WIFI认证服务器不在线,在海思平台外加一个usb wifi模块,mt7601 加载ok,配置网络ok,但不能ping通?...
  8. catia怎么创建约束快捷键_答疑 | CATIA结构树无法显示怎么办?
  9. Parcelable与Serializable的比较
  10. animation与transition区别