This article is mainly about Basic Operators and Optimization Usage
Python的运算符跟其他语言几乎完全一样,但是也有几个特殊的需要单独说明一下:
Python has lots of common operators as other programming languages, like c/c++ and java. However, there are some special ones which need to pay attention to:
/ 除法,如果除数,被除数全为整形,返回整形商数,否则返回浮点数 % 取余函数,得到除法的余数 ** 乘幂函数, x ** y <=> pow(x, y) // (地板除,我不知道名字怎么来的),可以返回商的整数部分,即使除数,被除数有浮点数. divmod 同时得到商数和余数,并返回一个tuple(这非常方便)
/ division, if both divisor and dividend are integer, return integer; otherwise, return float point. % remainder function, got the remainderof division ** power function, x ** y equals to pow(x, y) // floor division, return integer part of quotient, even there is float point number within divisor and dividend. divmod return integer quotient and remainder as a tuple. (It's quite convenient for developer)
测试如下:
Following are some examples:
*** Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. *** >>> 4/3 1 >>> 4/3.0 1.3333333333333333 >>> 4//3 1 >>> 4//3.0 1.0 >>> divmod(4,3) (1, 1) >>> divmod(4,3.0) (1.0, 1.0) >>> >>> >>> >>> 2**3 8 >>> pow(2,3) 8
Python中的+=, -+, *=...称为增量运算符,用于实现原地运算(in-place arithmetic),这些运算符可以用来优化程序性能,因为运算结果不会返回一个新的对象.
Python has increment operators, such as +=, -=, *=, and so on. They are used for in-place arithmetic to optimizing programme performance, because they will not return a new object.
Python中基本运算符:
Basic operators in Python:
运算符 描述 operators description lambda Lambda表达式 Lambda Expression or 布尔“或” logic or and 布尔“与” logic and not x 布尔“非” logic not in,not in 成员测试 member test is,is not 同一性测试 identity test <,<=,>,>=,!=,== 比较 comparison | 按位或 bit or ^ 按位异或 bit XOR & 按位与 bit and <<,>> 移位 shift +,- 加法与减法 addition and subtraction *,/,% 乘法、除法与取余 multiplication, division and remainder operators +x,-x 正负号 positive/negative sign ~x 按位翻转 bit NOT ** 指数 exponent x.attribute 属性参考 attribute reference x[index] 下标 index x[index:index] 寻址段 slice f(arguments...) 函数调用 function (experession,...) 绑定或元组显示 binding or tuple [expression,...] 列表显示 list {key:datum,...} 字典显示 dict 'expression,...' 字符串转换 string
No comments :
Post a Comment