Numbers 数字 Chapter Topics 本章主题 • Introduction to Numbers 数的简介 • Integers 整型 • Boolean 布尔型 • Standard Integers 标准的整型 • Long Integers 长整型 • Floating Point Real Numbers 浮点型实数 • Complex Numbers 复数 • Operators 操作符 • Built-in Functions 内建函数 • Other Numeric Types 其它数字类型 • Related Modules 相关模块 In this chapter, we will focus on Python’s numeric types. We will cover each type in detail, then present the various operators and built-in functions that can be used with numbers. We conclude this chapter by introducing some of the standard library modules that deal with numbers. 本章的主题是Python中的数字。我们会详细介绍每一种数字类型,它们适用的各种运算符, 以及用于处理数字的内建函数。在本章的末尾, 我们简单介绍了几个标准库中用于处理数字的模块。 5.1 Introduction to Numbers 5.1 数字类型 Numbers provide literal or scalar storage and direct access. A number is also an immutable type, meaning that changing or updating its value results in a newly allocated object. This activity is, of course, transparent to both the programmer and the user, so it should not change the way the application is developed. 数字提供了标量贮存和直接访问。它是不可更改类型,也就是说变更数字的值会生成新的对象。当然,这个过程无论对程序员还是对用户都是透明的,并不会影响软件的开发方式。 Python has several numeric types: “plain” integers, long integers, Boolean, double-precision floating point real numbers, decimal floating point numbers, and complex numbers. Python支持多种数字类型:整型、长整型、布尔型、双精度浮点型、十进制浮点型和复数。 How to Create and Assign Numbers (Number Objects) 如何创建数值对象并用其赋值 (数字对象) Creating numbers is as simple as assigning a value to a variable: 创建数值对象和给变量赋值一样同样简单: anInt = 1 aLong = -9999999999999999L aFloat = 3.1415926535897932384626433832795 aComplex = 1.23+4.56J How to Update Numbers 如何更新数字对象 You can “update” an existing number by (re)assigning a variable to another number. The new value can be related to its previous value or to a com- pletely different number altogether. We put quotes around update because you are not really changing the value of the original variable. Because num- bers are immutable, you are just making a new number and reassigning the reference. Do not be fooled by what you were taught about how variables contain values that allow you to update them. Python’s object model is more specific than that. 通过给数字对象(重新)赋值, 您可以“更新”一个数值对象。我们之所以给更新这两个字加上引号, 是因为实际上你并没有更新该对象的原始数值。这是因为数值对象是不可改变对象。Python的对象模型与常规对象模型有些不同。你所认为的更新实际上是生成了一个新的数值对象,并得到它的引用。 When we learned programming, we were taught that variables act like boxes that hold values. In Python, variables act like pointers that point to boxes. For immutable types, you do not change the contents of the box, you just point your pointer at a new box. Every time you assign another number to a variable, you are creating a new object and assigning it. (This is true for all immutable types, not just numbers.) 在学习编程的过程中, 我们一直接受这样的教育, 变量就像一个盒子, 里面装着变量的值。在Python中, 变量更像一个指针指向装变量值的盒子。 对不可改变类型来说, 你无法改变盒子的内容, 但你可以将指针指向一个新盒子。每次将另外的数字赋给变量的时候,实际上创建了一个新的对象并把它赋给变量.(不仅仅是数字,对于所有的不可变类型,都是这么回事) anInt += 1 aFloat = 2.718281828 How to Remove Numbers 如何删除数字对象 Under normal circumstances, you do not really “remove” a number; you just stop using it! If you really want to delete a reference to a number object, just use the del statement (introduced in Section 3.5.6). You can no longer use the variable name, once removed, unless you assign it to a new object; other- wise, you will cause a NameError exception to occur. 按照Python的法则, 你无法真正删除一个数值对象, 你仅仅是不再使用它而已。如果你实际上想删除一个数值对象的引用, 使用 del 语句(参见3.5.6小节)。 删除对象的引用之后, 你就不能再使用这个引用(变量名), 除非你给它赋一个新值。如果试图使用一个已经被删除的对象引用, 会引发NameError异常。 del anInt del aLong, aFloat, aComplex Okay, now that you have a good idea of how to create and update num- bers, let us take a look at Python’s four numeric types. 好了, 既然你已经了解如何创建和更新数值对象, 那么来看下Python的四种主要数字类型。 5.2 Integers 5.2整型 Python has several types of integers. There is the Boolean type with two pos- sible values. There are the regular or plain integers: generic vanilla integers recognized on most systems today. Python also has a long integer size; how- ever, these far exceed the size provided by C longs. We will take a look at these types of integers, followed by a description of operators and built-in functions applicable only to Python integer types. Python有几种整数类型。布尔类型是只有两个值的整型。常规整型是绝大多数现代系统都能识别的整型。Python也有长整数类型。然而,它表示的数值大小远超过C语言的长整数 。下面我们先来了解一下这些类型,然后再来研究那些用于Python整数类型的运算符和内建函数。 5.2.1 Boolean 5.2.1 布尔型 The Boolean type was introduced in Python 2.3. Objects of this type have two possible values, Boolean True and False. We will explore Boolean objects toward the end of this chapter in Section 5.7.1. Python 从版本 2.3 开始支持布尔类型。该类型的取值范围只有两个值,也就是布尔值True和布尔值False。我们会在本章的末尾一节5.7.1详细讲解布尔对象。 5.2.2 Standard (Regular or Plain) Integers 5.2.2 标准整数类型 Python’s “plain” integers are the universal numeric type. Most machines (32-bit) running Python will provide a range of 231 to 2311, that is 2, 147,483,648 to 2,147,483,647. If Python is compiled on a 64-bit system with a 64-bit compiler, then the integers for that system will be 64-bit. Here are some examples of Python integers: Python的标准整数类型是最通用的数字类型。在大多数32位机器上,标准整数类型的取值范围是-231 到231-1,也就是-2,147,483,648到 2,147,483,647。如果在 64 位机器上使用 64 位编译器编译Python,那么在这个系统上的整数将是64位。下面是一些Python标准整数类型对象的例子: 0101 84 -237 0x80 017 -680 -0X92 Python integers are implemented as (signed) longs in C. Integers are normally represented in base 10 decimal format, but they can also be speci- fied in base 8 or base 16 representation. Octal values have a “0” prefix, and hexadecimal values have either “0x” or “0X” prefixes. Python标准整数类型等价于C的(有符号)长整型。整数一般以十进制表示,但是Python也支持八进制或十六进制来表示整数。如果八进制整数以数字“0”开始, 十六进制整数则以 “0x” 或“0X” 开始。 5.2.3 Long Integers 5.2.3 长整型 The first thing we need to say about Python long integers (or longs for short) is not to get them confused with longs in C or other compiled languages—these values are typically restricted to 32- or 64-bit sizes, whereas Python longs are limited only by the amount of (virtual) memory in your machine. In other words, they can be very L-O-N-G longs. 关于Python长整数类型我们必须要提的是, 请不要将它和C或其它编译型语言的长整数类型混淆。那些语言的长整数典型的取值范围是32位或64位。Python的长整数类型能表达的数值仅仅与你的机器支持的(虚拟)内存大小有关, 换句话说, Python能轻松表达很大很大很大的整数。 Longs are a superset of integers and are useful when your application requires integers that exceed the range of plain integers, meaning less than 231 or greater than 2311. Use of longs is denoted by the letter “L”, uppercase (L) or lowercase (l), appended to the integer’s numeric value. Values can be expressed in decimal, octal, or hexadecimal. The following are examples of longs: 长整数类型是标准整数类型的超集, 当你的程序需要使用比标准整数类型更大的整数时, 长整数类型就有用武之地了。在一个整数值后面加个L(大写或小写都可以),表示这个整数是长整数。这个整数可以是十进制,八进制, 或十六进制。下面是一些长整数的例子: 16384L -0x4E8L 017L -2147483648l 052144364L 299792458l 0xDECADEDEADBEEFBADFEEDDEAL -5432101234L CORE STYLE: Use uppercase “L” with long integers 核心风格:用大写字母 “L”表示长整数 Although Python supports a case-insensitive “L” to denote longs, we recommend that you use only the uppercase “L” to avoid confusion with the number one (1). Python will display only longs with a capital “L .” As integers and longs are slowly being unified, you will only see the “L” with evaluatable string representations (repr()) of longs. Printable string representations(str()) will not have the “L .” 尽管 Python 也支持用小写字母 L 标记的长整型,但是我们郑重推荐您仅使用大写的 “L”,这样能有效避免数字1和小写L的混淆。Python在显示长整数类型数值的时候总是用大写“L ”,目前整型和长整型正在逐渐缓慢的统一,您只有在对长整数调用repr()函数时才有机会看到“L”,如果对长整数对象调用str()函数就看不到 L 。举例如下: >>> aLong = 999999999l >>> aLong 999999999L >>> print aLong 999999999 5.2.4 Unification of Integersand Long Integers 5.2.4整型和长整型的统一 Both integer types are in the process of being unified into a single integer type. Prior to Python 2.2, plain integer operations resulted in overflow (i.e., greater than the 232 range of numbers described above), but in 2.2 or after, there are no longer such errors. 这两种整数类型正在逐渐统一为一种。在Python 2.2以前,标准整数类型对象超出取值范围会溢出(比如上面提到的大于232的数),但是从Python2.2以后就再也没有这样的错误了。 Python 2.1 >>> 9999 ** 8 Traceback (most recent call last): File "", line 1, in ? OverflowError: integer exponentiation Python 2.2 >>> 9999 ** 8 99920027994400699944002799920001L Removing the error was the first phase. The next step involved bit-shifting; it used to be possible to left-shift bits out of the picture (resulting in 0): 移除这个错误是第一步。 下一步修改位移位; 左移比特导致出界(导致0值)在过去是经常可能发生的事; >>> 2 << 32 0 In 2.3 such an operation gives a warning, but in 2.4 the warning is gone, and the operation results in a real (long) value: 在Python2.3中, 这个操作产生一个警告, 不过在2.4版里移除了这个 Warning, 并且这步操作生成了一个真正的长整数。 Python 2.3 >>> 2 << 32 __main__:1: FutureWarning: x<>> 2 << 32 8589934592L there will no longer be a long type (at least not at the user level). Things will all happen quietly under the covers. Of course, those with C access will be able to enjoy both types as before, meaning, how- ever, that your C code will still need to be able to distinguish between the differ- ent Python integer types. You can read more about the unification of integers and longs in PEP 237. 不远的将来,至少普通用户会几乎感觉不到长整型的存在。必要时整型会悄悄自动转换为长整型。当然,那些要调用C的人仍然可以继续使用这两种整数类型, 因为C代码必须区分不同的整数类型。如果你想详细了解标准整型与长整型整合的信息,请阅读PEP237. 5.3 Double Precision FloatingPoint Numbers 5.3 双精度浮点数 Floats in Python are implemented as C doubles, double precision floating point real numbers, values that can be represented in straightforward decimal or scientific notations. These 8-byte (64-bit) values conform to the IEEE 754 definition (52M/11E/1S) where 52 bits are allocated to the mantissa, 11 bits to the exponent (this gives you about ± 10308.25 in range), and the final bit to the sign. That all sounds fine and dandy; however, the actual degree of precision you will receive (along with the range and overflow handling) depends com- pletely on the architecture of the machine as well as the implementation of the compiler that built your Python interpreter. Python中的浮点数类似C语言中的double类型, 是双精度浮点数,可以用直接的十进制或科学计数法表示。每个浮点数占8个字节(64比特),完全遵守IEEE754号规范(52M/11E/1S), 其中52个比特用于表示底,11个比特用于表示指数(可表示的范围大约是正负10的308.25次方), 剩下的一个比特表示符号。这看上去相当完美,然而,实际精度依赖于机器架构和创建Python解释器的编译器。 Floating point values are denoted by a decimal point ( . ) in the appropriate place and an optional “e” suffix representing scientific notation. We can use either lowercase ( e ) or uppercase ( E ). Positive (+) or negative ( - ) signs between the “e” and the exponent indicate the sign of the exponent. Absenceof such a sign indicates a positive exponent. Here are some floating point values: 浮点数值通常都有一个小数点和一个可选的后缀e(大写或小写,表示科学计数法)。在e和指数之间可以用正(+)或负(-)表示指数的正负(正数的话可以省略符号)。下面是一些典型的浮点数值的例子: 0.0 -777. 1.6 -5.555567119 96e3 * 1.0 4.3e25 9.384e-23 -2.172818 float(12) 1.000000001 3.1416 4.2E-10 -90. 6.022e23 -1.609E-19 5.4 Complex Numbers 5.4 复数 A long time ago, mathematicians were absorbed by the following equation: x2 = -1 The reason for this is that any real number (positive or negative) multiplied by itself results in a positive number. How can you multiply any number with itself to get a negative number? No such real number exists. So in the eigh- teenth century, mathematicians invented something called an imaginary num- ber i (or j, depending on what math book you are reading) such that: j  –1 在很久以前,数学家们被下面这样的等式困扰。 x2 = -1 这是因为任何实数(无论正数还是负数)乘以自己总是会得到一个非负数。一个数怎么可以乘以自己却得到一个负数?没有这样的实数存在。就这样, 直到18世纪, 数学家们发明了一个虚拟的数 i (或者叫j,看你读的是哪本教科书了) j=根号下-1 Basically a new branch of mathematics was created around this special number (or concept), and now imaginary numbers are used in numerical and math- ematical applications. Combining a real number with an imaginary number forms a single entity known as a complex number. A complex number is any ordered pair of floating point real numbers (x, y) denoted by x + yj where x is the real part and y is the imaginary part of a complex number. 基于这个特殊的数(或者称之为概念),数学从此有了一个新的分支。现在虚数已经广泛应用于数值和科学计算应用程序中。一个实数和一个虚数的组合构成一个复数。一个复数是一对有序浮点数(x, y)。表示为 x + yj, 其中x是实数部分,y是虚数部分。 It turns out that complex numbers are used a lot in everyday math, engineering, electronics, etc. Because it became clear that many researchers were reinventing this wheel quite often, complex numbers became a real Python data type long ago in version 1.4. 渐渐的复数在日常运算,机械,电子等行业获得了广泛的应用。由于一些研究人员不断的重复制造用于复数运算的工具, 在很久以前的Python1.4版本里,复数终于成为一个真正的Python数据类型。 Here are some facts about Python’s support of complex numbers: 下面是Python语言中有关复数的几个概念: • Imaginary numbers by themselves are not supported in Python (they are paired with a real part of 0.0 to make a complex number) 虚数不能单独存在,它们总是和一个值为0.0的实数部分一起来构成一个复数。 • Complex numbers are made up of real and imaginary parts 复数由实数部分和虚数部分构成 • Syntax for a complex number: real+imagj 表示虚数的语法: real+imagj • Both real and imaginary components are floating point values 实数部分和虚数部分都是浮点数 • Imaginary part is suffixed with letter “J” lowercase ( j) or uppercase (J) 虚数部分必须有后缀j或J。 The following are examples of complex numbers: 下面是一些复数的例子: 64.375+1j 4.23-8.5j 0.23-8.55j 1.23e-045+6.7e+089j 6.23+1.5j -1.23-875J 0+1j 9.80665-8.31441J -.0224+0j 5.4.1 Complex Number Built-in Attributes 5.4.1 复数的内建属性 Complex numbers are one example of objects with data attributes (Section 4.1.1). The data attributes are the real and imaginary components of the complex number object they belong to. Complex numbers also have a method attribute,that can be invoked, returning the complex conjugate of the object. 复数对象拥有数据属性(参见4.1.1节), 分别为该复数的实部和虚部。复数还拥有 conjugate方法, 调用它可以返回该复数的共轭复数对象。(两头牛背上的架子称为轭,轭使两头牛同步行走。共轭即为按一定的规律相配的一对——译者注) Table 5.1 Complex Number Attributes 表 5.1 复数属性 Attribute Description 属性 描述 num.real Real component of complex number 该复数的实部 num num.imag Imaginary component of complex 该复数的虚部 number num num.conjugate() Returns complex conjugate of num 返回该复数的共轭复数 >>> aComplex = -8.333-1.47j >>> aComplex (-8.333-1.47j) >>> aComplex.real -8.333 >>> aComplex.imag -1.47 >>> aComplex.这() (-8.333+1.47j) Table 5.1 describes the attributes of complex numbers. 表5.1描述了复数的所有属性 5.5 Operators 5.5 运算符 Numeric types support a wide variety of operators, ranging from the standard type of operators to operators created specifically for numbers, and even some that apply to integer types only. 数值类型可进行多种运算。从标准运算符到数值运算符,甚至还有专门的整数运算符。 5.5.1 Mixed-Mode Operations 5.5.1 混合模式运算符 It may be hard to remember, but when you added a pair of numbers in the past, what was important was that you got your numbers correct. Addition using the plus ( + ) sign was always the same. In programming languages, this may not be as straightforward because there are different types of numbers. 也许你还记得, 过去将两个数相加时, 你必须努力保证操作数是合适的类型。自然而然的, 加法总是使用 + 号, 然而在计算机语言看来这件事没那么简单,因为数字又有很多不同的类型。 When you add a pair of integers, the + represents integer addition, and when you add a pair of floating point numbers, the + represents double- precision floating point addition, and so on. Our little description extends even to non-numeric types in Python. For example, the + operator for strings represents concatenation, not addition, but it uses the same operator! The point is that for each data type that supports the + operator, there are dif- ferent pieces of functionality to “make it all work,” embodying the concept of overloading. 当两个整数相加时, + 号表示整数加法, 当两个浮点数相加时, + 表示浮点数加法, 依此类推。在Python中, 甚至非数字类型也可以使用 + 运算符。举例来说, 字符串A + 字符串B 并不表示加法操作, 它表示的是把这两个字符串连接起来, 生成一个新的字符串。关键之处在于支持 + 运算符的每种数据类型, 必须告诉Python, + 运算符应该如何去工作。 这也体现了重载概念的具体应用。 Now, we cannot add a number and a string, but Python does support mixed mode operations strictly between numeric types. When adding an integer and a float, a choice has to be made as to whether integer or floating point addition is used. There is no hybrid operation. Python solves this prob- lem using something called numeric coercion. This is the process whereby one of the operands is converted to the same type as the other before the operation. Python performs this coercion by following some basic rules. 虽然我们不能让一个数字和一个字符串相加, 但Python确实支持不同的数字类型相加。当一个整数和一个浮点数相加时, 系统会决定使用整数加法还是浮点数加法(实际上并不存在混合运算)。Python使用数字类型强制转换的方法来解决数字类型不一致的问题, 也就是说它会强制将一个操作数转换为同另一个操作数相同的数据类型。这种操作不是随意进行的, 它遵循以下基本规则。 To begin with, if both numbers are the same type, no conversion is neces- sary. When both types are different, a search takes place to see whether one number can be converted to the other’s type. If so, the operation occurs and both numbers are returned, one having been converted. There are rules that must be followed since certain conversions are impossible, such as turning a float into an integer, or converting a complex number to any non-complex number type. 首先,如果两个操作数都是同一种数据类型,没有必要进行类型转换。仅当两个操作数类型不一致时, Python才会去检查一个操作数是否可以转换为另一类型的操作数。如果可以,转换它并返回转换结果。由于某些转换是不可能的,比如果将一个复数转换为非复数类型, 将一个浮点数转换为整数等等,因此转换过程必须遵守几个规则。 Coercions that are possible, however, include turning an integer into a float (just add “.0”) or converting any non-complex type to a complex number (just add a zero imaginary component, e.g., “0j”). The rules of coercion follow from these two examples: integers move toward float, and all move toward complex. The Python Language Reference Guide describes the coerce() operation in the following manner. 要将一个整数转换为浮点数,只要在整数后面加个 .0 就可以了。 要将一个非复数转换为复数,则只需要要加上一个 “0j” 的虚数部分。这些类型转换的基本原则是: 整数转换为浮点数, 非复数转换为复数。 在Python语言参考中这样描述 coerce() 方法: • If either argument is a complex number, the other is converted to complex; 如果有一个操作数是复数, 另一个操作数被转换为复数。 • Otherwise, if either argument is a floating point number, the other is converted to floating point; 否则,如果有一个操作数是浮点数, 另一个操作数被转换为浮点数。 • Otherwise, if either argument is a long, the other is converted to long; 否则, 如果有一个操作数是长整数,则另一个操作数被转换为长整数; • Otherwise, both must be plain integers and no conversion is necessary (in the upcoming diagram, this describes the rightmost arrow). 否则,两者必然都是普通整数,无须类型转换。(参见下文中的示意图) The flowchart shown in Figure 5–1 illustrates these coercion rules. Automatic numeric coercion makes life easier for the programmer because he or she does not have to worry about adding coercion code to his or her application. If explicit coercion is desired, Python does provide the coerce() built-in function (described later in Section 5.6.2). 图5-1的流程图阐释了强制转换的规则。数字类型之间的转换是自动进行的,程序员无须自己编码处理类型转换。不过在确实需要明确指定对某种数据类型进行特殊类型转换的场合, Python提供了 coerce() 内建函数来帮助你实现这种转换。(见5.6.2小节) START with both numbers Either No complex? Either float? No Either No long int? Yes Yes Yes Both No complex? Both No float? Both No long int? Yes Yes Yes Convert non-complex to complex Convert non-float to float Convert non-long to long Perform the desired numeric computation and STOP Figure 5–1 Numeric coercion 图 5-1 数值类型转换 The following is an example showing you Python’s automatic coercion. In order to add the numbers (one integer, one float), both need to be converted to the same type. Since float is the superset, the integer is coerced to a float before the operation happens, leaving the result as a float: 下面演示一下Python的自动数据类型转换。为了让一个整数和一个浮点数相加, 必须使二者转换为同一类型。因为浮点数是超集,所以在运算开始之前, 整数必须强制转换为一个浮点数,运算结果也是浮点数: >>> 1 + 4.5 5.5 5.5.2 Standard Type Operators 5.5.2 标准类型运算符 The standard type operators discussed in Chapter 4 all work as advertised for numeric types. Mixed-mode operations, described above, are those which involve two numbers of different types. The values are internally converted to the same type before the operation is applied. 第四章中讲到的标准运算符都可以用于数值类型。上文中提到的混合模式运算问题, 也就是不同数据类型之间的运算, 在运算之前,Python内部会将两个操作数转换为同一数据类型。 Here are some examples of the standard type operators in action with numbers: 下面是一些数字标准运算的例子: >>> 5.2 == 5.2 True >>> -719 >= 833 False >>> 5+4e >= 2-3e True >>> 2 < 5 < 9 # same as ( 2 < 5 ) and ( 5 < 9 ) True >>> 77 > 66 == 66 # same as ( 77 > 66 ) and ( 66 == 66 ) True >>> 0. < -90.4 < 55.3e2 != 3 < 181 False >>> (-1 < 1) or (1 < -1) True 5.5.3 Numeric Type (Arithmetic) Operators 5.5.3 算术运算符 Python supports unary operators for no change and negation, + and -, respec- tively; and binary arithmetic operators +, -, *, /, %, and **, for addition, subtraction, multiplication, division, modulo, and exponentiation, respectively.In addition, there is a new division operator, //, as of Python 2.2. Python支持单目运算符正号(+)和负号(-), 双目运算符, +,-,*,/,%,还有 ** , 分别表示加法,减法, 乘法, 除法, 取余, 和幂运算。从Python2.2起,还增加了一种新的整除运算符 // 。 Division 除法 Those of you coming from the C world are intimately familiar with classic division—that is, for integer operands, floor division is performed, while for floating point numbers, real or true division is the operation. However, for those who are learning programming for the first time, or for those who rely on accurate calculations, code must be tweaked in a way to obtain the desired results. This includes casting or converting all values to floats before per- forming the division. 拥有C背景的程序员一定熟悉传统除法――也就是说, 对整数操作数,会执行“地板除”(floor,取比商小的最大整数。例如5除以2等于2.5,其中“2”就称为商的“地板”,即“地板除”的结果。本书中使用“地板除”的说法是为了沿用原作者的风格,译者注)。对浮点操作数会执行真正的除法。然而,对第一次学编程的人或者那些依赖精确计算的人来说,可能就需要多次调整代码才能得到自己想要的结果。 The decision has been made to change the division operator in some future version of Python from classic to true division and add another opera- tor to perform floor division. We now summarize the various division types and show you what Python currently does, and what it will do in the future. 在未来的Python版本中,Python开发小组已经决定改变 / 运算符的行为。/ 的行为将变更为真正的除法, 会增加一种新的运算来表示地板除。 下面我们总结一下Python现在的除法规则, 以及未来的除法规则: Classic Division When presented with integer operands, classic division truncates the fraction, returning an integer (floor division). Given a pair of floating-point operands, it returns the actual floating-point quotient (true division). This functionality is standard among many programming languages, including Python. Example: 传统除法 如果是整数除法, 传统除法会舍去小数部分,返回一个整数(地板除)。如果操作数之一是浮点数,则执行真正的除法。包括Python语言在内的很多语言都是这种行为。看下面的例子: >>> 1 / 2 # perform integer result (floor) # 地板除 0 >>> 1.0 / 2.0 # returns actual quotient #真正除法 0.5 True Division This is where division always returns the actual quotient, regardless of the type of the operands. In a future version of Python, this will be the algorithm of the division operator. For now, to take advantage of true division, one must give the from __future__ import division directive. Once that happens, the division operator ( / ) performs only true division: 真正的除法 除法运算总是返回真实的商, 不管操作数是整数还是浮点数。在未来版本的Python 中, 这将是除法运算的标准行为。现阶段通过执行 from __future__ import division 指令, 也可以做到这一点。 >>> from __future__ import division >>> >>> 1 / 2 # returns real quotient 0.5 >>> 1.0 / 2.0 # returns real quotient 0.5 Floor Division A new division operator ( // ) has been created that carries out floor division: it always truncates the fraction and rounds it to the next smallest whole number toward the left on the number line, regardless of the operands’ numeric types. This operator works starting in 2.2 and does not require the __future__ directive above. 地板除 从Python 2.2开始, 一个新的运算符 // 已经被增加进来, 以执行地板除: // 除法不管操作数何种数值类型,总是舍去小数部分,返回数字序列中比真正的商小的最接近的数字。 >>> 1 // 2 # floors result, returns integer # 地板除, 返回整数 0 >>> 1.0 // 2.0 # floors result, returns float # 地板除, 返回浮点数 0.0 >>> -1 // 2 # move left on number line # 返回比 –0.5小的整数, 也就是 -1 -1 There were strong arguments for as well as against this change, with the former from those who want or need true division versus those who either do not want to change their code or feel that altering the division operation from classic division is wrong. 关于除法运算的变更, 支持的人和反对的人几乎一样多。有些人认为这种变化是错误的, 有些人则不想修改自己的现有代码,而剩下的人则想要真正的除法。 This change was made because of the feeling that perhaps Python’s divi- sion operator has been flawed from the beginning, especially because Python is a strong choice as a first programming language for people who aren’t used to floor division. One of van Rossum’s use cases is featured in his “What’s New in Python 2.2” talk: 之所以会有这种变化是因为 Python的核心开发团队认为Python的除法运算从一开始就设计失误。特别是, 随着Python的逐渐发展, 它已经成为那些从未接触过地板除的人们的首选学习语言。Python语言的发明人 范•罗萨姆 在他的 《Python 2.2新增功能》一文中讲到: def velocity(distance, totalTime): rate = distance / totalTime As you can tell, this function may or may not work correctly and is solely dependent on at least one argument being a floating point value. As men- tioned above, the only way to ensure the correct value is to cast both to floats, i.e., rate = float(distance) / float(totalTime). With the upcoming change to true division, code like the above can be left as is, and those who truly desire floor division can use the new double-slash ( // ) operator. 你可能会说, 只要有一个参数为浮点数这个函数就能正常工作。像上面提到的那样,要确保它能正常工作需要强制将参数转换为浮点类型,也就是 rate = float(distance) / float(totalTime)。将来除法将变更为真正的除法,上面的代码可以无需更改正常工作。需要地板除的地方只需要改变为两个连续的 除号。 Yes, code breakage is a concern, and the Python team has created a set of scripts that will help you convert your code to using the new style of division. Also, for those who feel strongly either way and only want to run Python with a specific type of division, check out the -Qdivision_style option to the interpreter. An option of -Qnew will always perform true division while -Qold(currently the default) runs classic division. You can also help your users transition to new division by using -Qwarn or -Qwarnall. 是的, 代码会受到一些影响, Python团队已经创作了一系列脚本帮助你转换旧代码,以确保它能适应新的除法行为。而且对那些强烈需要某种除法行为的人来说, Python解释器提供了 Qdivision_style 启动参数。 -Qnew 执行新的除法行为, -Qold 则执行传统除法行为(默认为Qold)。你也可以帮助你的用户使用-Qwarn 或 –Qwarnall 参数度过过渡时期。 More information about this big change can be found in PEP 238. You can also dig through the 2001 comp.lang.python archives for the heated debates if you are interested in the drama. Table 5.2 summarizes the division operators in the various releases of Python and the differences in operation when you import new division functionality. 关于这次变化的详细信息可以参考 PEP238。如果你对这场论战感兴趣,也可以翻阅2001年的comp.lang.python 归档。 表5.2总结了除法运算符在不同Python版本中的行为差异。 Modulus 取余 Integer modulo is straightforward integer division remainder, while for float,it is the difference of the dividend and the product of the divisor and the 整数取余相当容易理解, 浮点数取余就略复杂些。 Table 5.2 Division Operator Functionality 表 5.2 除法操作符的行为 Operator 2.1.x and Older 操作符 2.1.x 及更早版本 2.2 and Newer (No Import) 2.2 及更新版本 (No import division) 2.2 and Newer (Import of division) 2.2 及更新版本 ( import division) / classic classic true 传统除 传统除 真正除 // n/a floor floor 无 地板除 地板除 quotient of the quantity dividend divided by the divisor rounded down to the closest integer, i.e., x - (math.floor(x/y) * y), or 商取小于等于精确值的最大整数的乘积之差. 即: x - (math.floor(x/y) * y) 或者 x x – -- ? y y For complex number modulo, take only the real component of the division result, i.e., x - (math.floor((x/y).real) * y). 对于复数,取余的定义类似于浮点数,不同之处在于商仅取其实数部分,即: x - (math.floor ((x/y).real) * y)。 Exponentiation 幂运算 The exponentiation operator has a peculiar precedence rule in its relationship with the unary operators: it binds more tightly than unary operators to its left, but less tightly than unary operators to its right. Due to this characteristic, you will find the ?? operator twice in the numeric operator charts in this text. Here are some examples: 幂运算操作符和一元操作符之间的优先级关系比较特别: 幂运算操作符比其左侧操作数的一元操作符优先级低,比 起右侧操作数的一元操作符的优先级高,由于这个特性你会在算术运算符表中找到两个 ** .下面举几个例子: >>> 3 ** 2 9 >>> -3 ** 2 # ** binds tighter than - to its left >>> -3 ** 2 # ** 优先级高于左侧的 - -9 >>> (-3) ** 2 # group to cause - to bind first >>> (-3) ** 2 # 加括号提高 -的优先级 9 >>> 4.0 ** -1.0 # ** binds looser than - to its right >>> 4.0 ** -1.0 # ** 优先级低于右侧的 - 0.25 In the second case, it performs 3 to the power of 2 (3-squared) before it applies the unary negation. We need to use the parentheses around the “?3”to prevent this from happening. In the final example, we see that the unary operator binds more tightly because the operation is 1 over quantity 4 to the 1 1 第2种情况下解释器先计算 3**2 再取其相反数,我们需要给"-3"加上括号来得到我们希望的结果。最后一个例子,结果是4**(-1),这是按照规定的优先级获得的结果. first power 4 1 or 4 . Note that 1 / 4 as an integer operation results in an inte ger 0, so integers are not allowed to be raised to a negative power (it is a float- ing point operation anyway), as we will show here: 注意 1/4 作为整数除法结果是 0 所以以整数为底进行负数指数运算会引发一个 negative power (负数指数)异常 >>> 4 ** -1 Traceback (innermost last): File "", line 1, in ? ValueError: integer to the negative power Summary 总结 Table 5.3 summarizes all arithmetic operators, in shaded hierarchical order from highest-to-lowest priority. All the operators listed here rank higher in priority than the bitwise operators for integers found in Section 5.5.4. 表5.3 总结了所有的算术运算符, 从上到下, 计算优先级依次降低。 这里列出的所有运算符都比即将在5.5.4小节讲到的位运算符优先级高。 Table 5.3 Numeric Type Arithmetic Operators 表 5.3 算术运算符 Arithmetic Operator Function 算术操作符 功能 expr1 ** expr2 Expr1 raised to the power of expr2a 表达式1 表达 表达式2 结果 +expr (unary) expr sign unchanged +expr 结果符号不变 -expr (unary) negation of expr 对结果符号取负 expr1 ** expr2 Expr1 raised to the power of expr2a 表达式1 表达式2 结果 expr1 * expr2 expr1 times expr2 表达式1 乘 表达式2 expr1 / expr2 expr1 divided by expr2 (classic or true division) 表达式1 除以 表达式2(传统除或真正除) expr1 // expr2 expr1 divided by expr2 (floor division [only]) 表达式1 地板除以 表达式2 expr1 % expr2 expr1 modulo expr2 表达式1 对表达式2 取余 expr1 + expr2 expr1 plus expr2 表达式1 加 表达式2 expr1 - expr2 expr1 minus expr2 表达式1 减 表达式2 a.  binds tighter than unary operators to its left and looser than unary operators to its right. 注:** 运算符优先级高于单目运算符 Here are a few more examples of Python’s numeric operators: 下面是更多Python数值运算的例子: >>> -442 - 77 -519 >>> >>> 4 ** 3 64 >>> >>> 4.2 ** 3.2 98.7183139527 >>> 8 / 3 2 >>> 8.0 / 3.0 2.66666666667 >>> 8 % 3 2 >>> (60. - 32.) * ( 5. / 9. ) 15.5555555556 >>> 14 * 0x04 56 >>> 0170 / 4 30 >>> 0x80 + 0777 639 >>> 45L * 22L 990L >>> 16399L + 0xA94E8L 709879L >>> -2147483648L - 52147483648L -54294967296L >>> 64.375+1j + 4.23-8.5j (68.605-7.5j) >>> 0+1j ** 2 # same as 0+(lj**2) (-1+0j) >>> 1+1j ** 2 # same as 1+(lj**2) 0j >>> (1+1j) ** 2 2j Note how the exponentiation operator is still higher in priority than the binding addition operator that delimits the real and imaginary components of a complex number. Regarding the last example above, we grouped the com- ponents of the complex number together to obtain the desired result. 注意指数运算符的优先级高于连接实部和虚部的+号运算符。就上面最后一个例子来说, 我们人为的加上了括号,这就改变运算顺序, 从而得到我们想要的结果。 5.5.4 *Bit Operators (Integer-Only) 5.5.4 *位运算符(只适用于整数) Python integers may be manipulated bitwise and the standard bit opera- tions are supported: inversion, bitwise AND, OR, and exclusive OR (aka XOR), and left and right shifting. Here are some facts regarding the bit operators: Python整数支持标准位运算:取反(~),按位 与(&), 或(|) 及 异或(^) 及左移(<<)和右移(>>)。Python这样处理位运算: • Negative numbers are treated as their 2’s complement value. 负数会被当成正数的2进制补码处理。 • Left and right shifts of N bits are equivalent to multiplication and division by (2  N) without overflow checking. 左移和右移N位等同于无溢出检查的2的N次幂运算: 2**N。 • For longs, the bit operators use a “modified” form of 2’s complement, acting as if the sign bit were extended infinitely to the left. 对长整数来说, 位运算符使用一种经修改的2进制补码形式,使得符号位可以无限的向左扩展。 The bit inversion operator ( ~ ) has the same precedence as the arith- metic unary operators, the highest of all bit operators. The bit shift operators ( << and >> ) come next, having a precedence one level below that of the standard plus and minus operators, and finally we have the bitwise AND, XOR, and OR operators (&, ^, | ), respectively. All of the bitwise operators are presented in the order of descending priority in Table 5.4. 取反(~)运算的优先级与数字单目运算符相同, 是所有位操作符中优先级最高的一个。 左移和右移运算的优先级次之,但低于加减法运算。与, 或, 异或 运算优先级最低。所有位运算符按优先级高低列在表 5.4 中。 Table 5.4 Integer Type Bitwise Operators 表5.4 整型位运算符 Bitwise Operator Function 位运算符 功能 ~num (unary) invert the bits of num, yielding -(num + 1) 单目运算,对数的每一位取反。结果为 -(num+1) num1 << num2 Num1 left shifted by num2 bits Num1 左移 num2 位 num1 >> num2 num1 right shifted by num2 bits Num1 右移 num2 位 num1 & num2 num1 bitwise AND with num2 num1 与 num2 按位 与 num1 ^ num2 num1 bitwise XOR (exclusive OR) with num2 num1 异或 num2 num1 | num2 num1 bitwise OR with num2 num1 与 num2 按位 或 Here we present some examples using the bit operators using 30 (011110), 45 (101101), and 60 (111100): 下面是几个使用整数30,45,60进行位运算的例子: >>> 30 & 45 12 >>> 30 | 45 63 >>> 45 & 60 44 >>> 45 | 60 61 >>> ~30 -31 >>> ~45 -46 >>> 45 << 1 90 >>> 60 >> 2 15 >>> 30 ^ 45 51 5.6 Built-in and Factory Functions 5.6 内建函数与工厂函数 5.6.1 Standard Type Functions 5.6.1 标准类型函数 In the last chapter, we introduced the cmp(), str(), and type() built-in functions that apply for all standard types. For numbers, these functions will compare two numbers, convert numbers into strings, and tell you a number’s type, respectively. Here are some examples of using these functions: 在上一章中, 我们介绍了 cmp(), str() 和 type() 内建函数。 这些函数可以用于所有的标准类型。对数字对象来说, 这些函数分别比较两个数的大小, 将数字转换为字符串, 以及返回数字对象的类型。 >>> cmp(-6, 2) -1 >>> cmp(-4.333333, -2.718281828) -1 >>> cmp(0xFF, 255) 0 >>> str(0xFF) '255' >>> str(55.3e2) '5530.0' >>> type(0xFF) >>> type(98765432109876543210L) >>> type(2-1j) 5.6.2 Numeric Type Functions 5.6.2 数字类型函数 Python currently supports different sets of built-in functions for numeric types. Some convert from one numeric type to another while others are more operational, performing some type of calculation on their numeric arguments. Python现在拥有一系列针对数字类型的内建函数。一些函数用于数字类型转换, 另一些则执行一些常用运算。 Conversion Factory Functions 转换工厂函数 The int(), long(), float(), and complex() functions are used to con- vert from any numeric type to another. Starting in Python 1.5, these func- tions will also take strings and return the numerical value represented by the string. Beginning in 1.6, int() and long() accepted a base parameter (see below) for proper string conversions—it does not work for numeric type conversion. 函数 int(), long(), float() 和 complex() 用来将其它数值类型转换为相应的数值类型。从 Python 1.5 版本开始, 这些函数也接受字符串参数, 返回字符串所表示的数值。从Python 1.6版开始,int() 和 long() 在转换字符串时,接受一个进制参数。如果是数字类型之间的转换,则这个进制参数不能使用。 A fifth function, bool(), was added in Python 2.2. At that time, it was used to normalize Boolean values to their integer equivalents of one and zero for true and false values. The Boolean type was added in Python 2.3, so true and false now had constant values of True and False (instead of one and zero). For more information on the Boolean type, see Section 5.7.1. 从Python2.2起, 有了第五个内建函数 bool()。它用来将整数值1和0转换为标准布尔值 True 和False. 从 Python2.3开始, Python的标准数据类型添加了一个新成员:布尔(Boolean)类型。从此 true 和 false 现在有了常量值即 True 和 False(不再是1和0)。要了解布尔类型的更多信息, 参阅5.7.1小节。 In addition, because of the unification of types and classes in Python 2.2, all of these built-in functions were converted into factory functions. Factory functions, introduced in Chapter 4, just means that these objects are now classes, and when you “call” them, you are just creating an instance of that class. 另外, 由于Python 2.2对类型和类进行了整合(这里指Python的传统风格类和新风格类——译者注), 所有这些内建函数现在都转变为工厂函数。我们曾经在第四章介绍过工厂函数,所谓工厂函数就是指这些内建函数都是类对象, 当你调用它们时,实际上是创建了一个类实例。 They will still behave in a similar way to the new Python user so it is probably something you do not have to worry about. 不过不用担心, 这些函数的使用方法并没有什么改变。 The following are some examples of using these functions: 下面是一些使用内建函数的示例: >>> int(4.25555) 4 >>> long(42) 42L >>> float(4) 4.0 >>> complex(4) (4+0j) >>> >>> complex(2.4, -8) (2.4-8j) >>> >>> complex(2.3e-10, 45.3e4) (2.3e-10+453000j) Table 5.5 summarizes the numeric type factory functions. 表5.5 数值工厂函数总结 Table 5.5 Numeric Type Factory Functions a 表5.5 数值工厂函数 Class (Factory Function) Operation 类(工厂函数) 操作 bool(obj) b Returns the Boolean value of obj, e.g., the value of executing obj.__nonzero__() 返回obj对象的布尔值,也就是 obj.__nonzero__()方法的返回值 int(obj, base=10) Returns integer representation of string or number obj; similar to string.atoi(); optional base argument introduced in 1.6 返回一个字符串或数值对象的整数表示, 类似string.atoi();从Python 1.6起,引入了可选的进制参数。 long(obj, base=10) Returns long representation of string or number obj; similar to string.atol(); optional base argument introduced in 1.6 返回一个字符或数据对象的长整数表示,类似string.atol(), 从Python1.6起, 引入了可选的进制参数 float(obj) Returns floating point representation of string or number obj; similar to string.atof() 返回一个字符串或数据对象的浮点数表示,类似string.atof() complex(str) or complex(real, imag=0.0) Returns complex number representation of str, or builds one given real (and perhaps imaginary) component(s) 返回一个字符串的复数表示,或者根据给定的实数(及一个可选的虚数部分)生成一个复数对象。 a. Prior to Python 2.3, these were all built-in functions. a. 在Python2.3之前, 这些都是内建函数 b. New in Python 2.2 as built-in function, converted to factory function in 2.3. b. Python2.2中新增的内建函数,在Python2.3中改变为工厂函数 Operational 功能函数 Python has five operational built-in functions for numeric types: abs(), coerce(), divmod(), pow(), and round(). We will take a look at each and present some usage examples. Python有五个运算内建函数用于数值运算: abs(), coerce(), divmod(), pow(), pow() 和 round()。我们将对这些函数逐一浏览,并给出一些有用的例子: abs() returns the absolute value of the given argument. If the argument is a complex number, then math.sqrt(num.real2 + num.imag2) is returned. Here are some examples of using the abs() built-in function: abs()返回给定参数的绝对值。如果参数是一个复数, 那么就返回math.sqrt(num.real2 + num.imag2)。下面是几个abs()函数的示例: >>> abs(-1) 1 >>> abs(10.) 10.0 >>> abs(1.2-2.1j) 2.41867732449 >>> abs(0.23 - 0.78) 0.55 The coerce() function, although it technically is a numeric type conver- sion function, does not convert to a specific type and acts more like an operator, hence our placement of it in our operational built-ins section. In Section 5.5.1, we discussed numeric coercion and how Python performs that operation. The coerce() function is a way for the programmer to explicitly coerce a pair of numbers rather than letting the interpreter do it. This feature is par- ticularly useful when defining operations for newly created numeric class types. coerce() just returns a tuple containing the converted pair of numbers. Here are some examples: 函数coerce(),尽管从技术上讲它是一个数据类型转换函数,不过它的行为更像一个运算符,因此我将它放到了这一小节。在5.5.1小节,我们讨论了Python如何执行数值类型转换。函数coerce()为程序员提供了不依赖Python解释器, 而是自定义两个数值类型转换的方法。对一种新创建的数值类型来说, 这个特性非常有用。函数coerce()仅回一个包含类型转换完毕的两个数值元素的元组。下面是几个例子: >>> coerce(1, 2) (1, 2) >>> >>> coerce(1.3, 134L) (1.3, 134.0) >>> >>> coerce(1, 134L) (1L, 134L) >>> >>> coerce(1j, 134L) (1j, (134+0j)) >>> >>> coerce(1.23-41j, 134L) ((1.23-41j), (134+0j)) The divmod() built-in function combines division and modulus opera- tions into a single function call that returns the pair (quotient, remainder) as a tuple. The values returned are the same as those given for the classic divi- sion and modulus operators for integer types. For floats, the quotient returned is math.floor(num1/num2) and for complex numbers, the quo- tient is math.floor((num1/num2).real). divmod()内建函数把除法和取余运算结合起来, 返回一个包含商和余数的元组。对整数来说,它的返回值就是地板除和取余操作的结果。对浮点数来说, 返回的商部分是math.floor(num1/num2),对复数来说, 商部分是ath.floor((num1/num2).real)。 >>> divmod(10,3) (3, 1) >>> divmod(3,10) (0, 3) >>> divmod(10,2.5) (4.0, 0.0) >>> divmod(2.5,10) (0.0, 2.5) >>> divmod(2+1j, 0.5-1j) (0j, (2+1j)) Both pow() and the double star ( ** ) operator perform exponentiation; however, there are differences other than the fact that one is an operator and the other is a built-in function. 函数 pow() 和双星号 (**) 运算符都可以进行指数运算。不过二者的区别并不仅仅在于一个是运算符,一个是内建函数。 The ** operator did not appear until Python 1.5, and the pow() built-in takes an optional third parameter, a modulus argument. If provided, pow() will perform the exponentiation first, then return the result modulo the third argument. This feature is used for cryptographic applications and has better performance than pow(x,y) % z since the latter performs the calculations in Python rather than in C-like pow(x, y, z). 在Python 1.5之前,并没有 ** 运算符。内建函数pow()还接受第三个可选的参数,一个余数参数。如果有这个参数的, pow() 先进行指数运算,然后将运算结果和第三个参数进行取余运算。这个特性主要用于密码运算,并且比 pow(x,y) % z 性能更好, 这是因为这个函数的实现类似于C函数 pow(x,y,z)。 >>> pow(2,5) 32 >>> >>> pow(5,2) 25 >>> pow(3.141592,2) 9.86960029446 >>> >>> pow(1+1j, 3) (-2+2j) The round() built-in function has a syntax of round(flt,ndig=0). It normally rounds a floating point number to the nearest integral number and returns that result (still) as a float. When the optional ndig option is given, round() will round the argument to the specific number of decimal places. 内建函数round()用于对浮点数进行四舍五入运算。它有一个可选的小数位数参数。如果不提供小数位参数, 它返回与第一个参数最接近的整数(但仍然是浮点类型)。第二个参数告诉round函数将结果精确到小数点后指定位数。 >>> round(3) 3.0 >>> round(3.45) 3.0 >>> round(3.4999999) 3.0 >>> round(3.4999999, 1) 3.5 >>> import math >>> for eachNum in range(10): ... print round(math.pi, eachNum) ... 3.0 3.1 3.14 3.142 3.1416 3.14159 3.141593 3.1415927 3.14159265 3.141592654 3.1415926536 >>> round(-3.5) -4.0 >>> round(-3.4) -3.0 >>> round(-3.49) -3.0 >>> round(-3.49, 1) -3.5 Note that the rounding performed by round() moves away from zero on the number line, i.e., round(.5) goes to 1 and round(-.5) goes to 1. Also, with functions like int(), round(), and math.floor(), all may seem like they are doing the same thing; it is possible to get them all confused. Here is how you can differentiate among these: 值得注意的是 round() 函数是按四舍五入的规则进行取整。也就是round(0.5)得到1, round(-0.5)得到-1。猛一看 int(), round(), math.floor() 这几个函数好像做的是同一件事, 很容易将它们弄混,是不是?下面列出它们之间的不同之处: • int() chops off the decimal point and everything after (aka truncation). 函数int()直接截去小数部分。(返回值为整数) • floor() rounds you to the next smaller integer, i.e., the next integer moving in a negative direction (toward the left on the number line). 函数floor()得到最接近原数但小于原数的整数。(返回值为浮点数) • round() (rounded zero digits) rounds you to the nearest integer period. 函数round()得到最接近原数的整数。(返回值为浮点数) Here is the output for four different values, positive and negative, and the results of running these three functions on eight different numbers. (We reconverted the result from int() back to a float so that you can visu- alize the results more clearly when compared to the output of the other two functions.) 的例子用四个正数和四个负数作为这三个函数的参数,将返回结果列在一起做个比较。(为了便于比较,我们将int()函数的返回值也转换成了浮点数)。 >>> import math >>> for eachNum in (.2, .7, 1.2, 1.7, -.2, -.7, -1.2, -1.7): ... print "int(%.1f)\t%+.1f" % (eachNum, float(int(each- Num))) ... print "floor(%.1f)\t%+.1f" % (eachNum, ... math.floor(eachNum)) ... print "round(%.1f)\t%+.1f" % (eachNum, round(eachNum)) ... print '-' * 20 ... int(0.2) +0.0 floor(0.2) +0.0 round(0.2) +0.0 -------------------- int(0.7) +0.0 floor(0.7) +0.0 round(0.7) +1.0 -------------------- int(1.2) +1.0 floor(1.2) +1.0 round(1.2) +1.0 -------------------- int(1.7) +1.0 floor(1.7) +1.0 round(1.7) +2.0 -------------------- int(-0.2) +0.0 floor(-0.2) -1.0 round(-0.2) +0.0 -------------------- int(-0.7) +0.0 floor(-0.7) -1.0 round(-0.7) -1.0 -------------------- int(-1.2) -1.0 floor(-1.2) -2.0 round(-1.2) -1.0 -------------------- int(-1.7) -1.0 floor(-1.7) -2.0 round(-1.7) -2.0 Table 5.6 summarizes the operational functions for numeric types. 表5.6 数值运算函数一览 Table 5.6 Numeric Type Operational Built-in Functionsa 表5.6 数值运算内建函数 Function Operation 函数 功能 abs(num) Returns the absolute value of num 返回 num 的绝对值 coerce(num1, num2) Converts num1 and num2 to the same numeric type and returns the converted pair as a tuple 将num1和num2转换为同一类型,然后以一个 元组的形式返回。 divmod(num1, num2) Division-modulo combination returns (num1 / num2, num1 % num2) as a tuple; for floats and complex, the quotient is rounded down (complex uses only real com- ponent of quotient) 除法-取余运算的结合。返回一个元组(num1/num2,num1 % num2)。对浮点数和复数的商进行下舍入(复数仅取实数部分的商) pow(num1, num2, mod=1) Raises num1 to num2 power, quantity modulo mod if provided 取 num1 的 num2次方,如果提供 mod参数,则计算结果再对mod进行取余运算 round(flt, ndig=0) (Floats only) takes a float flt and rounds it to ndig digits, defaulting to zero if not provided 接受一个浮点数 flt 并对其四舍五入,保存 ndig位小数。若不提供ndig 参数,则默认小数点后0位。 a. Except for round(), which applies only to floats. a. round()仅用于浮点数。(译者注:整数也可以, 不过并没有什么实际意义) 5.6.3 Integer-Only Functions 5.6.3 仅用于整数的函数 In addition to the built-in functions for all numeric types, Python supports a few that are specific only to integers (plain and long). These functions fall into two categories, base presentation with hex() and oct(), and ASCII conversion featuring chr() and ord(). 除了适应于所有数值类型的内建函数之外,Python还提供一些仅适用于整数的内建函数(标准整数和长整数)。这些函数分为两类,一类用于进制转换,另一类用于ASCII转换。 Base Representation 进制转换函数 As we have seen before, Python integers automatically support octal and hexadecimal representations in addition to the decimal standard. Also, Python has two built-in functions that return string representations of an integer’s octal or hexadecimal equivalent. These are the oct() and hex() built-in functions, respectively. They both take an integer (in any representa- tion) object and return a string with the corresponding value. The following are some examples of their usage: 前面我们已经看到,除了十进制标准,Python整数也支持八进制和16进制整数。 除此之外, Python还提供了两个内建函数来返回字符串表示的8进制和16进制整数。它们分别是 oct() 和 hex()。它们都接受一个整数(任意进制的)对象,并返回一个对应值的字符串对象。下面是几个示例: >>> hex(255) '0xff' >>> hex(23094823l) '0x1606627L' >>> hex(65535*2) '0x1fffe' >>> >>> oct(255) '0377' >>> oct(23094823l) '0130063047L' >>> oct(65535*2) '0377776' ASCII Conversion ASCII 转换函数 Python also provides functions to go back and forth between ASCII(American Standard Code for Information Interchange) characters and their ordinal integer values. Each character is mapped to a unique number in a table numbered from 0 to 255. This number does not change for all computers using the ASCII table, providing consistency and expected pro- gram behavior across different systems. chr() takes a single-byte integer value and returns a one-character string with the equivalent ASCII charac- ter. ord() does the opposite, taking a single ASCII character in the form of a string of length one and returns the corresponding ASCII value as an integer: Python也提供了ASCII(美国标准信息交换码)码与其序列值之间的转换函数。每个字符对应一个唯一的整数(0-255)。对所有使用ASCII表的计算机来说, 这个数值是不变的。这保证了不同系统之间程序行为的一致性。函数chr()接受一个单字节整数值,返回一个字符串,其值为对应的字符。函数ord()则相反,它接受一个字符,返回其对应的整数值。 >>> ord('a') 97 >>> ord('A') 65 >>> ord('0') 48 >>> chr(97) 'a' >>> chr(65L) 'A' >>> chr(48) '0' Table 5.7 shows all built-in functions for integer types. 表5.7 列出了用于整数类型的所有内建函数 Table 5.7 Integer Type Built-in Functions 表5.7 仅适用于整数的内建函数 Function Operation 函数 操作 hex(num) Converts num to hexadecimal and returns as string 将数字转换成十六进制数并以字符串形式返回 oct(num) Converts num to octal and returns as string 将数字转换成八进制数并以字符串形式返回 chr(num) Takes ASCII value num and returns ASCII character as string; 0 <= num <= 255 only 将ASCII值的数字转换成ASCII字符,范围只能是0 <= num <= 255。 ord(chr) Takes ASCII or Unicode chr (string of length 1) and returns corresponding ordinal ASCII value or Unicode code point, respectively 接受一个 ASCII 或 Unicode 字符(长度为1的字符串),返回相应的ASCII值或Unicode 值。 unichr(num) Takes a Unicode code point value num and returns its Unicode character as a Unicode string; valid range depends on whether your Python was built as UCS-2 or UCS-4 接受Unicode码值,返回 其对应的Unicode字符。所接受的码值范围依赖于你的Python是构建于UCS-2还是UCS-4。 5.7 Other Numeric Types 5.7 其他数字类型 5.7.1 Boolean “Numbers” 5.7.1 布尔“数” Boolean types were added to Python starting in version 2.3. Although Boolean values are spelled “True” and “False,” they are actually an integer subclass and will behave like integer values one and zero, respectively, if used in a numeric context. Here are some of the major concepts surrounding Boolean types: 从Python2.3开始,布尔类型添加到了Python中来。尽管布尔值看上去是“True” 和“False,但是事实上是整型的子类,对应与整数的1和0。下面是有关布尔类型的主要概念: • They have a constant value of either True or False. 有两个永不改变的值True 或False。 • Booleans are subclassed from integers but cannot themselves be further derived. 布尔型是整型的子类,但是不能再被继承而生成它的子类。 • Objects that do not have a __nonzero__() method default to True. 没有__nonzero__()方法的对象的默认值是True。 • Recall that Python objects typically have a Boolean False value for any numeric zero or empty set. 对于值为零的任何数字或空集(空列表、空元组和空字典等)在Python中的布尔值都是False。 • Also, if used in an arithmetic context, Boolean values True and False will take on their numeric equivalents of 1 and 0, respectively. 在数学运算中,Boolean值的True和False分别对应于1和 0。 • Most of the standard library and built-in Boolean functions that previously returned integers will now return Booleans. 以前返回整数的大部分标准库函数和内建布尔型函数现在返回布尔型。 • Neither True nor False are keywords yet but will be in a future version. True和False现在都不是关键字,但是在Python将来的版本中会是。 All Python objects have an inherent True or False value. To see what they are for the built-in types, review the Core Note sidebar in Section 4.3.2. Here are some examples using Boolean values: 所有Python对象都有一个内建的True或False值,对内建类型来说,这个值究竟是True还是False请参阅章节4.3.2中的核心备注。下面是使用内建类型布尔值的一些例子: # intro >>> bool(1) True >>> bool(True) True >>> bool(0) False >>> bool('1') True >>> bool('0') True >>> bool([]) False >>> bool ( (1,) ) True # 使用布尔数 >>> foo = 42 >>> bar = foo < 100 >>> bar True >>> print bar + 100 101 >>> print '%s' % bar True >>> print '%d' % bar 1 # 无 __nonzero__() >>> class C: pass >>> c = C() >>> >>> bool(c) True >>> bool(C) True # 重载 __nonzero__() 使它返回 False >>> class C: ... def __nonzero__(self): ... return False ... >>> c = C() >>> bool(c) False >>> bool(C) True # 哦,别这么干!! (无论如何不要这么干!) >>> True, False = False, True >>> bool(True) False >>> bool(False) True You can read more about Booleans in the Python documentation and PEP 285. 你可以在Python文档和PEP 285看到有关布尔类型的知识。 5.7.2 Decimal Floating Point Numbers 5.7.2 十进制浮点数 Decimal floating point numbers became a feature of Python in version 2.4 (see PEP 327), mainly because statements like the following drive many (scientific and financial application) programmers insane (or at least enrage them): 从Python2.4起(参阅PEP327)十进制浮点制成为一个Python特性。这主要是因为下面的语句经常会让一些编写科学计算或金融应用程序的程序员抓狂: >>> 0.1 0.1000000000000001 Why is this? The reason is that most implementations of doubles in C are done as a 64-bit IEEE 754 number where 52 bits are allocated for the man- tissa. So floating point values can only be specified to 52 bits of precision, and in situations where you have a(n endlessly) repeating fraction, expansions of such values in binary format are snipped after 52 bits, resulting in rounding errors like the above. The value .1 is represented by 0.11001100110011 . . .  为什么会这样?这是因为语言绝大多数C语言的双精度实现都遵守IEEE 754规范,其中52位用于底。因此浮点值只能有52位精度,类似这样的值的二进制表示只能象上面那样被截断。0.1的二进制表示是0.11001100110011 . . . 3 2 because its closest binary approximation is .0001100110011 . . ., or 1/16 + 1/32 + 1/256 + . . . 因为最接近的二进制表示就是.0001100110011...或 1/16 +1/32 + 1/256 + . . . As you can see, the fractions will continue to repeat and lead to the round- ing error when the repetition cannot “be continued.” If we were to do the same thing using a decimal number, it looks much “better” to the human eye because they have exact and arbitrary precision. Note in the below that you cannot mix and match decimals and floating point numbers. You can create decimals from strings, integers, or other decimals. You must also import the decimal module to use the Decimal number class. 你可以看到,这些片断不停的重复直到舍入出错。如果我们使用十进制来做同样的事情,感觉就会好很多,看上去会有任意的精度。注意下面,你不能混用十进制浮点数和普通的浮点数。你可以通过字符串或其它十进制数创建十进制数浮点数。你必须导入 decimal 模块以便使用 Decimal 类: >>> from decimal import Decimal >>> dec = Decimal(.1) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/decimal.py", line 523, in __new__ raise TypeError("Cannot convert float to Decimal. " + TypeError: Cannot convert float to Decimal. First convert the float to a string >>> dec = Decimal('.1') >>> dec Decimal("0.1") >>> print dec 0.1 >>> dec + 1.0 Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/decimal.py", line 906, in __add__ other = _convert_other(other) File "/usr/local/lib/python2.4/decimal.py", line 2863, in _convert_other raise TypeError, "You can interact Decimal only with int, long or Decimal data types." TypeError: You can interact Decimal only with int, long or Decimal data types. >>> >>> dec + Decimal('1.0') Decimal("1.1") >>> print dec + Decimal('1.0') 1.1 You can read more about decimal numbers in the PEP as well as the Python documentation, but suffice it to say that they share pretty much the same numeric operators as the standard Python number types. Since it is a specialized numeric type, we will not include decimals in the remainder of this chapter. 你可以从 Python文档中读取相关的 PEP 以了解十进制数。值得庆幸的是,十进制数和其它数值类型一样, 可以使用同样的算术运算符。由于十进制数本质上是一种用于数值计算的特殊类, 我们在本章的剩余部分将不再专门讲解十进制数。 5.8 Related Modules 5.8 相关模块 There are a number of modules in the Python standard library that add on to the functionality of the operators and built-in functions for numeric types. Table 5.8 lists the key modules for use with numeric types. Refer to the literature or online documentation for more information on these modules. 在Python标准库中有不少专门用于处理数值类型对象的模块,它们增强并扩展了内建函数的功能和数值运算的功能。 表5.8列出了几个比较核心的模块。要详细了解这些模块,请参阅这些模块的文献或在线文档。 For advanced numerical and scientific mathematics applications, there are well-known third-party packages Numeric (NumPy) and SciPy, which may be of interest to you. More information on those two packages can be found at: 对高级的数字科学计算应用来说,你会对著名的第三方包 Numeric(NumPy) 和SciPy感兴趣。关于这两个包的详细请访问下面的网址。 http://numeric.scipy.org/ http://scipy.org/ Table 5.8 Numeric Type Related Modules 表5.8 数字类型相关模块 Module Contents 模块 介绍 decimal Decimal floating point class Decimal 十进制浮点运算类 Decimal array Efficient arrays of numeric values (characters, ints, floats, etc.) 高效数值数组(字符,整数,浮点数等等) math/cmath Standard C library mathematical functions; most functions available in math are implemented for complex numbers in the cmath module 标准C库数学运算函数。常规数学运算在match模块,复数运算在cmath模块 operator Numeric operators available as function calls, i.e., opera- tor.sub(m, n) is equivalent to the difference (m - n) for numbers m and n 数字运算符的函数实现。比如 tor.sub(m,n)等价于 m - n random Various pseudo-random number generators (obsoletes rand and whrandom) 多种伪随机数生成器 CORE MODULE: random 核心模块: random The random module is the general-purpose place to go if you are looking for random numbers.This module comes with various pseudo-random number generators and comes seeded with the current timestamp so it is ready to go as soon as it has loaded. Here are some of the most commonly used functions in the random module: 当你的程序需要随机数功能时,random 模块就能派上用场。该模块包含多个伪随机数发生器,它们均以当前的时间戳为随机数种子。这样只要载入这个模块就能随时开始工作。下面列出了该模块中最常用的函数: randint() Takes two integer values and returns a random integer between those values inclusive 两个整数参数,返回二者之间的随机整数 randrange() Takes the same input as range() and returns a random integer that falls within that range 它接受和 range()函数一样的参数, 随机返回 range([start,]stop[,step])结果的一项 uniform() Does almost the same thing as randint(), but returns a float and is inclusive only of the smaller number (exclusive of the larger number) 几乎和 randint()一样,不过它返回的是二者之间的一个浮点数(不包括范围上限)。 random() Works just like uniform() except that the smaller number is fixed at 0.0, and the larger number is fixed at 1.0 类似 uniform() 只不过下限恒等于0.0,上限恒等于1.0 choice() Given a sequence (see Chapter 6), randomly selects and returns a sequence item 随机返回给定序列(关于序列,见第六章)的一个元素 We have now come to the conclusion of our tour of all of Python’s numeric types. A summary of operators and built-in functions for numeric types is given in Table 5.9. 到这儿,我们的 Python 数值类型之旅就该结束了。表5.9总结了数值类型的所有内建函数和运算符。 Table 5.9 Operators and Built-in Functions for All Numeric Types 表5.9 数值类型运算符和内建函数 Operator/ Built-in Description Int Long Float Complex Resulta 运算符/内建函数 描述 整型 长整型 浮点型 复数 结果 abs() Absolute value • • • • number a 取绝对值 chr() Character • • str 取对应的字符 coerce() Numeric coercion • • • • tuple 强制类型转换 complex() Complex factory 复数工厂函数 • • • • complex Function divmod() Division/modulo • • • • Tuple 除法及取余 float() Float factory function • • • • Float 浮点工厂函数 hex() Hexadecimal string • • Str 整数转16进制 int() Int factory function • • • • Int 整数工厂函数 long() Long factory function • • • • long 长整数工厂函数 oct() Octal string • • str ord() Ordinal (str) int 字符序数 pow() 指数操作 round() 四舍五入 **b 指数运算 +c 单目加 -c 单目减 ~c 按位取反 **b Exponentiation • • • • Number 指数运算 * Multiplication • • • • number 乘法运算 / Classic or true division • • • • number 传统或真正除法 // Floor division • • • • number 地板除 % Modulo/remainder • • • • number 取余 Table 5.9 Operators and Built-in Functions for All Numeric Types (continued) 表5.9 数值类型运算符和内建函数(续表) Operator/ Built-in Description Int Long Float Complex Resulta + Addition • • • • number 加法 - Subtraction • • • • number 减法 << Bit left shift • • int/long 位左移 >> Bit right shift • • int/long 位右移 & Bitwise AND • • int/long 按位与运算 ^ Bitwise XOR • • int/long 按位异或运算 | Bitwise OR •ˇ •ˇˇ int/long 按位或运算 a. A result of “number” indicates any of the four numeric types, perhaps the same as the operands. 结果为 number 表示可以为所有四种数值类型,可能与操作数相同 b.  has a unique relationship with unary operators; see Section 5.5.3 and Table 5.2. ** 与单目运算符有特殊关系,参阅 5.5.3小节和表5.2 c. Unary operator. 单目运算符 5.9 Exercises 5.9 练习 The exercises in this chapter may first be implemented as applications. Once full functionality and correctness have been verified, we recommend that the reader convert his or her code to functions that can be used in future exercises. On a related note, one style suggestion is not to use print statements in functions that return a calculation. The caller can perform any output desired with the return value. This keeps the code adaptable and reusable. 本章的练习可以先通过应用程序的形式实现。一旦功能齐备并且调试通过, 建议读者将自己的代码功能用函数封装起来,以便 在后面的练习中重用代码。关于编程风格我在这儿提醒一下,最好不要在函数内使用 print 语句输出信息,而是通过 return 语句返回必要的值。 这样调用函数的代码就可以自己处理显示方式。这样你的代码就适应性更广,更便于重用。 5–1. Integers. Name the differences between Python’s regular and long integers. 5-1整形 讲讲Python普通整型和长整型的区别 5–2. Operators. (a) Create a function to calculate and return the product of two numbers. (b) The code which calls this function should display the result. 5-2运算符 (a) 写一个函数,计算并返回两个数的乘积 (b) 写一段代码调用这个函数,并显示它的结果 5–3. Standard Type Operators. Take test score input from the user and output letter grades according to the following grade scale/curve: A: 90–100 B: 80–89 C: 70–79 D: 60–69 F: <60 5-3标准类型运算符. 写一段脚本,输入一个测验成绩,根据下面的标准,输出他的评分成绩(A-F)。 A: 90–100 B: 80–89 C: 70–79 D: 60–69 F: <60 5–4. Modulus. Determine whether a given year is a leap year, using the following formula: a leap year is one that is divisible by four, but not by one hundred, unless it is also divisible by four hundred. For example, 1992, 1996, and 2000 are leap years, but 1967 and 1900 are not. The next leap year falling on a century is 2400. 5-4取余。判断给定年份是否是闰年。使用下面的公式: 一个闰年就是指它可以被4整除,但不能被100整除, 或者它既可以被4又可以被100整除。比如 1992,1996和2000年是闰年,但1967和1900则不是闰年。下一个是闰年的整世纪是 2400 年。 5–5. Modulus. Calculate the number of basic American coins given a value less than 1 dollar. A penny is worth 1 cent, a nickel is worth 5 cents, a dime is worth 10 cents, and a quarter is worth 25 cents. It takes 100 cents to make 1 dollar. So given an amount less than 1 dollar (if using floats, con- vert to integers for this exercise), calculate the number of each type of coin necessary to achieve the amount, maxi- mizing the number of larger denomination coins. For example, given $0.76, or 76 cents, the correct output would be “3 quarters and 1 penny.” Output such as “76 pennies” and “2 quarters, 2 dimes, 1 nickel, and 1 penny” are not acceptable. 5-5取余。取一个任意小于1美元的金额,然后计算可以换成最少多少枚硬币。硬币有1美分,5美分,10美分,25美分四种。1美元等于100美分。举例来说,0.76美元换算结果应该是 3枚25美分,1枚1美分。类似76枚1美分,2枚25美分+2枚10美分+1枚5美分+1枚1美分这样的结果都是不符合要求的。 5–6. Arithmetic. Create a calculator application. Write code that will take two numbers and an operator in the format: N1 OP N2, where N1 and N2 are floating point or integer values, and OP is one of the following: +, -, *, /, %, **, representing addition, subtraction, multiplication, division, modulus/ remainder, and exponentiation, respectively, and displays the result of carrying out that operation on the input operands. Hint: You may use the string split() method, but you cannot use the exal() built-in function. 5-6算术。写一个计算器程序 你的代码可以接受这样的表达式,两个操作数加一个运算符:N1 运算符 N2. 其中 N1 和 N2为整数或浮点数,运算符可以是+, -, *, /, %, ** 分别表示加法,减法, 乘法, 整数除,取余和幂运算。计算这个表达式的结果,然后显示出来。提示: 可以使用字符串方法 split(),但不可以使用内建函数 eval(). 5–7. Sales Tax. Take a monetary amount (i.e., floating point dollar amount [or whatever currency you use]), and determine a new amount figuring all the sales taxes you must pay where you live. 5-7营业税。随意取一个商品金额,然后根据当地营业税额度计算应该交纳的营业税。 5–8. Geometry. Calculate the area and volume of: (a) squares and cubes (b) circles and spheres 5-8几何。计算面积和体积: (a) 正方形 和 立方体 (b) 圆 和 球 5–9. Style. Answer the following numeric format questions: (a) Why does 17 + 32 give you 49, but 017 + 32 give you 47 and 017 + 032 give you 41, as indicated in the examples below? 数值形式 回答下面关于数值格式的问题: (a) 为什么下面的例子里 17+32 等于49, 而 017+32等于47, 017+032等于41? >>> 17 + 32 49 >>> 017+ 32 47 >>> 017 + 032 41 (b) Why do we get 134L and not 1342 in the example below? (b)为什么下面这个表达式我们得到的结果是 134L 而不是1342 ? >>> 56l + 78l 134L 5–10. Conversion. Create a pair of functions to convert Fahrenheit to Celsius temperature values. C = (F - 32) * (5 / 9) should help you get started. We recommend you try true divi- sion with this exercise, otherwise take whatever steps are necessary to ensure accurate results. 5-10转换。写一对函数来进行华氏度到摄氏度的转换。转换公式为C = (F - 32) * (5 / 9) 应该在这个练习中使用真正的除法, 否则你会得到不正确的结果。 5–11. Modulus. (a) Using loops and numeric operators, output all even num- bers from 0 to 20. (b) Same as part (a), but output all odd numbers up to 20. (c) From parts (a) and (b), what is an easy way to tell the dif- ference between even and odd numbers? (d) Using part (c), write some code to determine if one num- ber divides another. In your solution, ask the user for both numbers and have your function answer “yes” or “no” as to whether one number divides another by returning True or False, respectively. 5-11 取余。 (a) 使用循环和算术运算,求出 0-20之间的所有偶数 (b) 同上,不过这次输出所有的奇数 (c) 综合 (a) 和 (b), 请问辨别奇数和偶数的最简单的方法是什么? (d) 使用(c)的成果,写一个函数,检测一个整数能否被另一个整数整除。 先要求用户输入两个数,然后你的函数判断两者是否有整除关系,根据判断结果分别返回 True 和 False; 5–12. Limits. Determine the largest and smallest ints, floats, andcomplex numbers that your system can handle. 5-12系统限制。写一段脚本确认一下你的Python所能处理的整数,长整数,浮点数和复数的范围。 5–13. Conversion. Write a function that will take a time period measured in hours and minutes and return the total time in minutes only. 5-13转换。写一个函数把由小时和分钟表示的时间转换为只用分钟表示的时间。 5–14. Bank Account Interest. Create a function to take an interest percentage rate for a bank account, say, a Certificate of Deposit (CD). Calculate and return the Annual Percentage Yield (APY) if the account balance was compounded daily. 5-14银行利息。写一个函数,以定期存款利率为参数, 假定该账户每日计算复利,请计算并返回年回报率。 5–15. GCD and LCM. Determine the greatest common divisor and least common multiple of a pair of integers. 最大公约数和最小公倍数。请计算两个整数的最大公约数和最小公倍数。 5–16. Home Finance. Take an opening balance and a monthly pay- ment. Using a loop, determine remaining balances for suc- ceeding months, including the final payment. “Payment 0” should just be the opening balance and schedule monthly payment amount. The output should be in a schedule format similar to the following (the numbers used in this example are for illustrative purposes only): 5-16家庭财务。给定一个初始金额和月开销数, 使用循环,确定剩下的金额和当月的支出数, 包括最后的支出数。 Payment() 函数会用到初始金额和月额度, 输出结果应该类似下面的格式(例子中的数字仅用于演示): Enter opening balance:100.00 Enter monthly payment: 16.13 Amount Remaining Pymt# Paid Balance ----- ------ --------- 0 $ 0.00 $100.00 1 $16.13 $ 83.87 2 $16.13 $ 67.74 3 $16.13 $ 51.61 4 $16.13 $ 35.48 5 6 $16.13 $16.13 $ 19.35 $ 3.22 5–17. Random Numbers. Read up on the random module and do the following problem: Generate a list of a random number (1 < N <= 100) of random numbers (0 <= n <= 231 -1). Then randomly select a set of these numbers (1 <= N <= 100), sort them, and display this subset. 5-17 随机数。熟读随机数模块然后解下面的题: 生成一个有 N 个元素的由随机数 n 组成的列表, 其中 N 和 n的取值范围分别为: (1 < N <= 100), (0 <= n <= 231 -1)。然后再随机从这个列表中取 N (1 <= N <= 100)个随机数出来, 对它们排序,然后显示这个子集。