变幻莫测的python(一)---基本数据类型
2014-04-05 23:31
417 查看
python一切皆对象,无论是数据类型变量等
两个变量可以有相同的内存地址,因为引用同一地址
算术运算符:+,-,*,/,**(求幂),//(整除),%
关系运算符:<,>,<=,>=,!=,==
逻辑运算符:and,or,not(非,取反)
逻辑运算:or
逻辑运算:and
逻辑运算:not
成员测试:in,not in
同一测试:is,is not
比较:<,<=,>,>=,!=,==
按位或:|
按位异或:^
按位与:&
移位:<<,>>
加法与减法:+,-
乘法,除法与取余:*,/,%
正负号:+x,-x
按位取反:~x
指数:**
无int和long概念,统一为int(class) 类型,包括int和long即两种类型合并为一种int(class)类型
-整形 范围:-2147483648到2147483647
-长整形
-浮点型 数字后面跟小数点即为浮点型a=3. float(class)
-复数型 数字后面跟J或j表示复杂类型比如抛物线,坐标 a=3.0j a+=66 -->(66+3j) complex(class)
a=('a',8) b=[a,'f',9] b[0]=('b',88)-->可以 b[0][0]='f'-->不可变,元组不能改变 好似java中pojo getset方法
可变集合:set
不可变集合:frozenset
具体很多操作方法,比如遍历,去除等都可以使用help()来查看对象
+ :链接2个序列
* :重复序列长度
in :判断元素是否在序列中
max() :返回最大的值---字符串序列
min() :返回最小的值---字符串序列
题外话:关于切片的原理,每个字符串或序列都可以通过索引来得到相应的单个对象,而这在python jvm中是怎么实现的呢,我的猜想是这样的,每个变量声明之后,这个标签对应并不是直接内存中对象(比如整个字符串对象),而是一个表,这个表维护了单个字符串或序列对象的内存位置,每次索引到是根据这个表维护的真实地址去找到对应的单个对象的
注:在使用中可以使用help获取帮助,还有就是一切皆对象,无论是数据类型还是自定义类型
列表和字典也是一样的皆对象,就不列举了,可以自己直接试试
1.变量
变量是一个内存标签,可以通过id(v)来查看内存地址两个变量可以有相同的内存地址,因为引用同一地址
>>> a=1 >>> b='a' >>> c='a' >>> d=1 >>> id(a) 505911008 >>> id(b) 23430592 >>> id(c) 23430592 >>> id(d) 505911008 >>>数据类型即为对象,声明时候即已经在内存中开辟一块内存空间,而变量名字相当于这块对象空间的标号,所以相同的对象标号内存地址一样。
2.运算符
赋值运算符:=,+=,-=,*=,/=,%=算术运算符:+,-,*,/,**(求幂),//(整除),%
关系运算符:<,>,<=,>=,!=,==
逻辑运算符:and,or,not(非,取反)
>>> a=1 >>> a+=1 >>> a 2 >>> a-=1 >>> a 1 >>> a*=1 >>> a 1 >>> a/=1 >>> a 1.0 >>> a//=1 >>> a 1.0 >>> a*=4 >>> a 4.0 >>> a**=3 >>> a 64.0 >>> a%=8 >>> a 0.0 >>> b=78 >>> a<b True >>> a==b False >>> a and b 0.0 >>> a or b 78 >>> not a True >>> not b False >>>
3.优先级(由低到高)---编程中用括号代替即可
Lambda逻辑运算:or
逻辑运算:and
逻辑运算:not
成员测试:in,not in
同一测试:is,is not
比较:<,<=,>,>=,!=,==
按位或:|
按位异或:^
按位与:&
移位:<<,>>
加法与减法:+,-
乘法,除法与取余:*,/,%
正负号:+x,-x
按位取反:~x
指数:**
>>> a=23 >>> b=45 >>> a^b 58 >>> a!=b True >>> a|b 63 >>> a&b 5 >>> a<<b 809240558043136 >>> -a -23 >>> ~a -24 >>> a**b 18956258430116202791319715713277227626159289499745290235663543 >>>
4.数据类型
数字
注:在python2.x中分为整形类型和长整形类型,使用type得到int(type(class))类型和long(type(class))类型(可以在数字后面加上L或l变为长整形),在python3中无int和long概念,统一为int(class) 类型,包括int和long即两种类型合并为一种int(class)类型
-整形 范围:-2147483648到2147483647
-长整形
-浮点型 数字后面跟小数点即为浮点型a=3. float(class)
-复数型 数字后面跟J或j表示复杂类型比如抛物线,坐标 a=3.0j a+=66 -->(66+3j) complex(class)
>>> a=1 >>> a=1L SyntaxError: invalid syntax >>> a=1l SyntaxError: invalid syntax >>> type(a) <class 'int'> >>> a=1.0 >>> type(a) <class 'float'> >>> a=3j >>> type(a) <class 'complex'> >>> a=3J >>> type(a) <class 'complex'> >>> a+=89 >>> a (89+3j) >>>
字符串
使用单引号或双引号或三重引号(三重引号用于注释或变量-相当于文本换行) str(class) 转意:\",\'>>> a='abc' >>> a 'abc' >>> a="let's go" >>> a "let's go" >>> a="""jjjj hahahah wowowo我可以 换行啊 因为是三重引号 “”“""" >>> a 'jjjj\nhahahah\nwowowo我可以\n换行啊\n因为是三重引号\n“”“' >>> a="我要使用(\"和\')" >>> a '我要使用("和\')' >>>
序列:
可以通过索引或者切片获取值得数据类型(字符串也可以),字典通过key取值-列表
使用中括号[],列表时可变的,列表类型可以包括所有类型,且可任意改变类型,但是包括元组时候不能通过索引改变元组类型(元组不可变)a=('a',8) b=[a,'f',9] b[0]=('b',88)-->可以 b[0][0]='f'-->不可变,元组不能改变 好似java中pojo getset方法
>>> a='abc' >>> b=1 >>> c=[a,b,'def',888,999.0] >>> c ['abc', 1, 'def', 888, 999.0] >>> c[0] 'abc' >>> c[0]=999 >>> c [999, 1, 'def', 888, 999.0] >>> d=[c,a,b] >>> d [[999, 1, 'def', 888, 999.0], 'abc', 1] >>> d[0][1]='ttt' >>> d [[999, 'ttt', 'def', 888, 999.0], 'abc', 1] >>> type(d) <class 'list'> >>>
-元组
使用小括号(),且元组不可改变,(元组中的列表是可以改变的),可以包含所有种类型a=(3,"ff",90.0) b=(a,'ff') b[0][1]-->'ff' 好似java中pojo>>> a='abc' >>> b='d' >>> c=888 >>> d=(a,b,c,'ll',0.999) >>> d ('abc', 'd', 888, 'll', 0.999) >>> d[0] 'abc' >>> d[0]='ooo' Traceback (most recent call last): File "<pyshell#394>", line 1, in <module> d[0]='ooo' TypeError: 'tuple' object does not support item assignment >>> type(d) <class 'tuple'> >>> e=['aa',999] >>> f=(e,'kkk') >>> f[0][1]='ooo'#元组中的列表可以被修改 >>> f (['aa', 'ooo'], 'kkk') >>> type(f) <class 'tuple'> >>>
-字典
使用花括号{},是映射类型(hash),字典对象时可变的,但是字典的键必须是不可变的(所以列表不能作为key),且不重复(重复的key会默认取最后一个字典对象) 相当于java中的map>>> a='abc' >>> b='def' >>> c={a:b,'a':'b',1:900,1:'aaa',2:['a',888],'y':(1,'34')} >>> c {1: 'aaa', 'a': 'b', 2: ['a', 888], 'abc': 'def', 'y': (1, '34')}#key 1为重复值,对应只取最后一个1 key对应的对象 >>> type(c) <class 'dict'> >>> c[1] 'aaa' >>> c[a] 'def' >>>
-集合
使用{},集合中的值是不能重复的,重复的值会被覆盖掉,且不能被索引查找,不支持切片可变集合:set
>>> a={'c',1,1,'d'} >>> type(a) <class 'set'> >>> a {1, 'd', 'c'} >>> a.add('u') >>> a {1, 'u', 'd', 'c'} >>> for u in a: print (u) 1 u d c >>> 'y' in a False >>> 'u' not in a False >>> a=set('jjjjjj9') >>> a {'j', '9'} >>>
不可变集合:frozenset
>>> a=frozenset('uuufs') >>> type(a) <class 'frozenset'> >>> a.add('i') Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> a.add('i') AttributeError: 'frozenset' object has no attribute 'add' >>> a frozenset({'s', 'f', 'u'}) >>> for u in a: print(u) s f u >>> 'p' in a False >>> 's' in a True >>>
具体很多操作方法,比如遍历,去除等都可以使用help()来查看对象
5.序列的基本操作
len() :求序列长度+ :链接2个序列
* :重复序列长度
in :判断元素是否在序列中
max() :返回最大的值---字符串序列
min() :返回最小的值---字符串序列
>>> a='asfllkk' >>> b=(a,'ooooo',999) >>> c=[b,'iii',888] >>> d={a:a,b:b,c:c,'a':1,1:'a'} Traceback (most recent call last): File "<pyshell#438>", line 1, in <module> d={a:a,b:b,c:c,'a':1,1:'a'} TypeError: unhashable type: 'list' >>> d={a:a,b:b,'c':c,'a':1,1:'a'} >>> len(a) 7 >>> len(b) 3 >>> len(c) 3 >>> len(d) 5 >>> a+b Traceback (most recent call last): File "<pyshell#444>", line 1, in <module> a+b TypeError: Can't convert 'tuple' object to str implicitly >>> a+a 'asfllkkasfllkk' >>> b+b ('asfllkk', 'ooooo', 999, 'asfllkk', 'ooooo', 999) >>> a*a Traceback (most recent call last): File "<pyshell#447>", line 1, in <module> a*a TypeError: can't multiply sequence by non-int of type 'str' >>> a*len(a) 'asfllkkasfllkkasfllkkasfllkkasfllkkasfllkkasfllkk' >>> 'a' in a True >>> a in a True >>> b in a Traceback (most recent call last): File "<pyshell#451>", line 1, in <module> b in a TypeError: 'in <string>' requires string as left operand, not tuple >>> 'fffs' in a False >>> 'c' in d True >>> 888 in c True >>> min(a) 'a' >>> min(d) Traceback (most recent call last): File "<pyshell#458>", line 1, in <module> min(d) TypeError: unorderable types: int() < str() >>> min(c) Traceback (most recent call last): File "<pyshell#459>", line 1, in <module> min(c) TypeError: unorderable types: str() < tuple() >>> min(b) Traceback (most recent call last): File "<pyshell#460>", line 1, in <module> min(b) TypeError: unorderable types: int() < str() >>>
6.切片
使用[]其中:出现为一次或两次,[数字一:数字二:数字三] 数字一二代表切片的范围,数字三代表切片的step,不能为0,其中正数为正切负数为反切>>> a='abcdefghijklmnopqrstuvwxyz' >>> a[1:6] 'bcdef' >>> a[0:6] 'abcdef' >>> a[0:6:2] 'ace' >>> a[::-1] 'zyxwvutsrqponmlkjihgfedcba' >>> a[::1] 'abcdefghijklmnopqrstuvwxyz' >>> a[::-2] 'zxvtrpnljhfdb' >>> a[-1:-3] '' >>> a[-1:-3:-1] 'zy' >>> a[1:] 'bcdefghijklmnopqrstuvwxyz' >>> a[-1:] 'z' >>> a[-3:-1] 'xy' >>> a[-3:1] '' >>> a[-3:1:-1] 'xwvutsrqponmlkjihgfedc' >>> >>> a[1:-3] 'bcdefghijklmnopqrstuvw' >>>
题外话:关于切片的原理,每个字符串或序列都可以通过索引来得到相应的单个对象,而这在python jvm中是怎么实现的呢,我的猜想是这样的,每个变量声明之后,这个标签对应并不是直接内存中对象(比如整个字符串对象),而是一个表,这个表维护了单个字符串或序列对象的内存位置,每次索引到是根据这个表维护的真实地址去找到对应的单个对象的
>>> a='abc' >>> id(a[0]) 23102912 >>> id(a) 25636032 >>> b=('abc','a') >>> id(b) 33528968 >>> id(b[0]) 34223968 >>> c='abc' >>> id(c) 25636032 >>> id(b[1]) 23102912 >>> d='a' >>> id(d) 23102912 >>> id(b[0][0]) 23102912 >>>
注:在使用中可以使用help获取帮助,还有就是一切皆对象,无论是数据类型还是自定义类型
>>> a=1 >>> type(a) <class 'int'> >>> help(a) Help on int object: class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal 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 to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Methods defined here: | | __abs__(...) | x.__abs__() <==> abs(x) | | __add__(...) | x.__add__(y) <==> x+y | | __and__(...) | x.__and__(y) <==> x&y | | __bool__(...) | x.__bool__() <==> x != 0 | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(...) | x.__divmod__(y) <==> divmod(x, y) | | __eq__(...) | x.__eq__(y) <==> x==y | | __float__(...) | x.__float__() <==> float(x) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(...) | x.__floordiv__(y) <==> x//y | | __format__(...) | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getnewargs__(...) | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __index__(...) | x[y:z] <==> x[y.__index__():z.__index__()] | | __int__(...) | x.__int__() <==> int(x) | | __invert__(...) | x.__invert__() <==> ~x | | __le__(...) | x.__le__(y) <==> x<=y | | __lshift__(...) | x.__lshift__(y) <==> x<<y | | __lt__(...) | x.__lt__(y) <==> x<y | | __mod__(...) | x.__mod__(y) <==> x%y | | __mul__(...) | x.__mul__(y) <==> x*y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __neg__(...) | x.__neg__() <==> -x | | __or__(...) | x.__or__(y) <==> x|y | | __pos__(...) | x.__pos__() <==> +x | | __pow__(...) | x.__pow__(y[, z]) <==> pow(x, y[, z]) | | __radd__(...) | x.__radd__(y) <==> y+x | | __rand__(...) | x.__rand__(y) <==> y&x | | __rdivmod__(...) | x.__rdivmod__(y) <==> divmod(y, x) | | __repr__(...) | x.__repr__() <==> repr(x) | | __rfloordiv__(...) | x.__rfloordiv__(y) <==> y//x | | __rlshift__(...) | x.__rlshift__(y) <==> y<<x | | __rmod__(...) | x.__rmod__(y) <==> y%x | | __rmul__(...) | x.__rmul__(y) <==> y*x | | __ror__(...) | x.__ror__(y) <==> y|x | | __round__(...) | Rounding an Integral returns itself. | Rounding with an ndigits argument also returns an integer. | | __rpow__(...) | y.__rpow__(x[, z]) <==> pow(x, y[, z]) | | __rrshift__(...) | x.__rrshift__(y) <==> y>>x | | __rshift__(...) | x.__rshift__(y) <==> x>>y | | __rsub__(...) | x.__rsub__(y) <==> y-x | | __rtruediv__(...) | x.__rtruediv__(y) <==> y/x | | __rxor__(...) | x.__rxor__(y) <==> y^x | | __sizeof__(...) | Returns size in memory, in bytes | | __str__(...) | x.__str__() <==> str(x) | | __sub__(...) | x.__sub__(y) <==> x-y | | __truediv__(...) | x.__truediv__(y) <==> x/y | | __trunc__(...) | Truncating an Integral returns itself. | | __xor__(...) | x.__xor__(y) <==> x^y | | bit_length(...) | int.bit_length() -> int | | Number of bits necessary to represent self in binary. | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | from_bytes(...) | int.from_bytes(bytes, byteorder, *, signed=False) -> int | | Return the integer represented by the given array of bytes. | | The bytes argument must either support the buffer protocol or be an | iterable object producing bytes. Bytes and bytearray are examples of | built-in objects that support the buffer protocol. | | The byteorder argument determines the byte order used to represent the | integer. If byteorder is 'big', the most significant byte is at the | beginning of the byte array. If byteorder is 'little', the most | significant byte is at the end of the byte array. To request the native | byte order of the host system, use `sys.byteorder' as the byte order value. | | The signed keyword-only argument indicates whether two's complement is | used to represent the integer. | | to_bytes(...) | int.to_bytes(length, byteorder, *, signed=False) -> bytes | | Return an array of bytes representing an integer. | | The integer is represented using length bytes. An OverflowError is | raised if the integer is not representable with the given number of | bytes. | | The byteorder argument determines the byte order used to represent the | integer. If byteorder is 'big', the most significant byte is at the | beginning of the byte array. If byteorder is 'little', the most | significant byte is at the end of the byte array. To request the native | byte order of the host system, use `sys.byteorder' as the byte order value. | | The signed keyword-only argument determines whether two's complement is | used to represent the integer. If signed is False and a negative integer | is given, an OverflowError is raised. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T >>> a.__add__(8) 9 >>>
>>> a='abc' >>> a.find('c') 2 >>> 'abc'.find('d') -1 >>> type('') <class 'str'> >>> help(str) Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str …………………………
>>> a=(1,'c') >>> type(a) <class 'tuple'> >>> type(()) <class 'tuple'> >>> a.count('c') 1 >>> ().count('c') 0 >>> help(()) Help on tuple object: class tuple(object) | tuple() -> empty tuple | tuple(iterable) -> tuple initialized from iterable's items
列表和字典也是一样的皆对象,就不列举了,可以自己直接试试
相关文章推荐
- 06python 之基本数据类型
- python 基本数据类型
- python——基本数据类型+常用操作符+循环
- Python学习之基本数据类型(一)
- Python基本数据类型
- Python基本数据类型之dict
- Python学习笔记一:数据类型与基本操作
- python基础教程之基本数据类型和变量声明介绍
- python中没有字符(char)这一基本数据类型
- Python数据类型之“序列概述与基本序列类型(Basic Sequences)”
- Python快速学习02:基本数据类型 & 序列
- python基本数据类型
- python基本知识之数据类型
- Python学习之路-初学篇之Python的基本数据类型(一)
- Python基本数据类型详细介绍(转)
- Python(2):基本数据类型
- python基本数据类型——list
- python基本数据类型——set
- python 基本数据类型
- python 【第二篇】python基本数据类型