3.3python中的xrangee是不是取消了

5283人阅读
Python(42)
1、range多用作循环,range(0,10)返回一个range对象,如想返回一个list,前面加上list转换;
2、arange是numpy模块中的函数,使用前需要先导入此模块,arange(3):返回array类型对象。
【注:range()中的步长不能为小数,但是np.arange()中的步长可以为小数】
3、xrange()也是用作循环,只是xrang(0,10)不返回list,返回xrange对象。每次调用返回其中的一个值。&
返回很大的数的时候或者频繁的需要break时候,xrange性能更好。
【注意:python3.x中把xrange()取消了】
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:248464次
积分:3242
积分:3242
排名:第10541名
原创:75篇
转载:135篇
(1)(1)(1)(8)(9)(10)(5)(9)(7)(7)(17)(37)(12)(26)(13)(4)(14)(5)(1)(5)(10)(3)(3)(3)3 Built-in Data Types - 简书
3 Built-in Data Types
basic numeric data type in Python is a 1-dimensional scalar which may be either an integer or a double-precision floating point, depending on the formatting of the number when input.
3.1 Variable names
Variable names with a single leading underscores indicate that the variable is for internal use by a module or class. While indicated to be private, this variable will generally be accessible by calling code.
Double leading underscores, for example __some_private_value indicate that a value is actually private and is not accessible.
3.2 Core Native Data Types
3.2.1 Numeric
integers, floats or complex.
python donnot have a fixed size and so can accommodate numbers which are largeer than maximum the basic integer type can handle.
3.2.1.1 Floating Point
two ways to generate a float
&&& x = 1.0
&&& x = float(1)
3.2.1.2 Complex
two ways, first, using j or the function complex()
&&&x = 2 + 3j
&&&x= complex(1)
3.2.1.3 Integers(int and long)
int() can generate an integer
integers can range from -2^31 to 2^31 -1
another integer, known as a long integer, which has no effective range limitation. Long integers are entered using the syntax x = 1L or by calling long(). and Python will automatically convert integers outside of the standard integer range to long integers.
3.2.2 Boolean
keywords: True and False.
also two methods to generate:
x = bool(1)
x = bool(0)
non-zero, non-empty values generally evaluate to true when evaluated by bool().
Zero or empty values such as bool(0), bool(0.0j), bool(NOne), bool(''), bool([]) are all false.
3.2.3 Strings
3.2.3.1 Slicing a String
s[ i : j ] = characters i,…, j - 1
s[ i : j : m] = characters i, i + m, …, i + m[ (j - i) /m ]
s[ -i, -j ] = characters n- i, … , n - j -1
n = len(string), the inde of the last character is n - 1, called by s[-1]
3.2.4 List
3.2.4.2 List Function
list.append( value)
append value to the end of the llist.
return the number of elements in the list.
list.extend( list 2 )
append the value of
list 2 to the end of the list.
list.pop( index )
return the value at the given index and remove the value of the list.
list.remove( value )
remove the first occurence of value from the list.
list.count( value )
count the number of occurence of value in the list.
del x[ slice ]
delete the elements in slice.
3.2.5 Tuple
just close to a list but are immutable.
list use [ ] to construct a list, tuple use ( ) and you can also use the function tuple().
Note that tuples containing a single element must contain a comma when created, so that x = (2, ) is assign a tuple to x, while x = (2) assign 2 to x. The latter interprets the parentheses as if they are part of a mathematical formula rather than being used to construct a tuple. x = tuple([2]) can be used to creat a single element tuple.
3.2.6 Xrange
for i in range(1, 10) is fundamental, xrange(a, b, i) creates the sequences that follow the pattern a, a + i, a + 2i.
xrange(b) is the same as xrange(0, b, 1)
3.2.7 Dictionary
Dictionaries are composed of keys(words) and values(definitions). keys must be unique data types(e.g. strings, the most common key), and values can contain any valid Python data type.
set and frozenset only differ in that the latter is immutable, frozenset to set is similar with a tuple to list. Set is not so important but they can be useful when working with messy data.
&&& x = set([’MSFT’,’GOOG’,’AAPL’,’HPQ’,’MSFT’])
{’AAPL’, ’GOOG’, ’HPQ’, ’MSFT’}
3.2.8.1 Set Functions
set.add(element)
append element to a set
returns the number of elements in the set
set.difference(set 2)
return the elements in set which are not in set 2.
set.intersection(set 2)
return the elements of x which are also in set.
set.remove(element)
remove element from the set.
set.union(set 2)
return the set containing all elements of set and set2.
3.3 Python and memory management
To save memory, y = x, x and y point to the same data in computer's memory. x and y sahre the same ID. However, once x is changed, x's ID changed but y's did not, indicating that the data in each variable was stored in different locations. this behavior is both safe and efficient, and common in basic Python immutable types such as int, long, float, complex, string, tuple, frozenset and xrange.
List has a different story. y = x, and x is a list, this assignment does not creat a copy and so change to either variable affect both.
slicing a list copy a list of any immutable parts. if x = [[1, 2], [3, 4]] , y = x, chage to x[0][0] also change y. A function has to be used to copy all mutable parts.
&&& import copy as cp
&&& x=[[0,1],[2,3]]
&&& y = cp.deepcopy(x)python3.4学习笔记(四) 3.x和2.x的区别
在2.x中:print html,3.x中必须改成:print(html)
import urllib2ImportError: No module named 'urllib2' 在python3.x里面,用urllib.request代替urllib2
import threadImportError: No module named 'thread'在python3.x里面,用_thread(在前面加一个下划线)代替thread
在2.x中except Exception,e : 3.x中改为except (Exception):
=================================print函数虽然print语法是Python 3中一个很小的改动,且应该已经广为人知,但依然值得提一下:Python 2中的print语句被Python 3中的print()函数取代,这意味着在Python 3中必须用括号将需要输出的对象括起来。在Python 2中使用额外的括号也是可以的。但反过来在Python 3中想以Python2的形式不带括号调用print函数时,会触发SyntaxError。Python 2.7.6
print 'Python', python_version()print 'Hello, World!'print('Hello, World!')print "text", ; print 'print more text on the same line'输出:Hello, World!Hello, World!text print more text on the same line---------------------------
Python 3.4.1print('Python', python_version())print('Hello, World!') print("some text,", end="") print(' print more text on the same line')输出:Hello, World!some text, print more text on the same lineprint 'Hello, World!'File "&ipython-input-3-139a7c5835bd&", line 1print 'Hello, World!'^SyntaxError: invalid syntax
注意:在Python中,带不带括号输出&Hello World&都很正常。但如果在圆括号中同时输出多个对象时,就会创建一个元组,这是因为在Python 2中,print是一个语句,而不是函数调用。
print 'Python', python_version()print('a', 'b')print 'a', 'b'Python 2.7.7('a', 'b')a b
---------------------------------整数除法由于人们常常会忽视Python 3在整数除法上的改动(写错了也不会触发Syntax Error),所以在移植代码或在Python 2中执行Python 3的代码时,需要特别注意这个改动。
所以,我还是会在Python 3的脚本中尝试用float(3)/2或 3/2.0代替3/2,以此来避免代码在Python 2环境下可能导致的错误(或与之相反,在Python 2脚本中用from __future__ import division来使用Python 3的除法)。
Python 2.7.63 / 2 = 13 // 2 = 13 / 2.0 = 1.53 // 2.0 = 1.0
Python 3.4.13 / 2 = 1.53 // 2 = 13 / 2.0 = 1.53 // 2.0 = 1.0---------------------------------UnicodePython 2有基于ASCII的str()类型,其可通过单独的unicode()函数转成unicode类型,但没有byte类型。而在Python 3中,终于有了Unicode(utf-8)字符串,以及两个字节类:bytes和bytearrays。
Python 2.7.6print type(unicode('this is like a python3 str type'))&type 'unicode'&print type(b'byte type does not exist')&type 'str'&print 'they are really' + b' the same'they are really the sameprint type(bytearray(b'bytearray oddly does exist though'))&type 'bytearray'&
Python 3.4.1 has &class 'bytes'&print('and Python', python_version(), end="")print(' also has', type(bytearray(b'bytearrays')))and Python 3.4.1 also has &class 'bytearray'&1'note that we cannot add a string' + b'bytes for data'---------------------------------------------------------------------------TypeError Traceback (most recent call last)&ipython-input-13-d3e8942ccf81& in &module&()----& 1 'note that we cannot add a string' + b'bytes for data'
TypeError: Can't convert 'bytes' object to str implicitly
=================================
python 2.4 与 python 3.0 的比较一、 print 从语句变为函数
1,2+3改为: print ( 1,2+3 )
二、range 与 xrange原 : range( 0, 4 )
结果 是 列表 [0,1,2,3 ]改为:list( range(0,4) )原 : xrange( 0, 4 )
适用于 for 循环的变量控制改为:range(0,4)
三、字符串原: 字符串以 8-bit 字符串存储改为: 字符串以 16-bit Unicode 字符串存储 四、try except 语句的变化在2.x中except Exception,e : 3.x中改为except (Exception):
五、打开文件原: file( ..... )
或 open(.....)改为:
只能用 open(.....)六、从键盘录入一个字符串原: raw_input( "提示信息" )改为: input( "提示信息" )
七、bytes 数据类型A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 &= x & 256.bytes 可以看成是&字节数组&对象,每个元素是 8-bit 的字节,取值范围 0~255。由于在 python 3.0中字符串以 unicode 编码存储,当写入二进制文件时,字符串无法直接写入(或读取),必须以某种方式的编码为字节序列后,方可写入。
(一)字符串编码(encode) 为 bytes例:
s = "张三abc12"
b = s.encode( 编码方式)
# b 就是 bytes 类型的数据
# 常用的编码方式为 : "uft-16"
, "utf-8", "gbk", "gb2312", "ascii" , "latin1" 等
# 注 : 当字符串不能编码为指定的&编码方式&时,会引发异常(二) bytes 解码(decode)为字符串
s = "张三abc12"
b = s.encode( "gbk")
# 字符串 s 编码为 gbk 格式的字节序列
s1 = b.decode("gbk")
# 将字节序列 b以gbk格式 解码为字符串
# 说明,当字节序列不能以指定的编码格式解码时会引发异常(三)使用方法举例#coding=gbkf = open("c:\\1234.txt", "wb")s = "张三李四abcd1234"# -------------------------------# 在 python2.4 中我们可以这样写:# f.write( s )# 但在 python 3.0中会引发异常# -------------------------------b = s.encode("gbk")f.write( b )f.close()input("?")读取该文件的例子:#coding=gbkf = open("c:\\1234.txt", "rb")f.seek(0,2) #定位至文件尾n = f.tell() #读取文件的字节数f.seek(0,0) #重新定位至文件开始处b = f.read( n )# ------------------------------# 在 python 2.4 中 b 是字符串类型# 要 python 3.0 中 b 是 bytes 类型# 因此需要按指定的编码方式确码# ------------------------------ s = b.decode("gbk")print ( s )# ------------------------------# 在 python 2.4 中 可以写作 print s 或 print ( s )# 要 python 3.0 中 必须写作 print ( s )# ------------------------------ f.close()input("?")运行后应显示:张三李四abcd1234 (四) bytes序列,一但形成,其内容是不可变的,例:s="ABCD"b=s.encode("gbk")print b[0]
65b[0] = 66
# 执行该句,出现异常: 'bytes' object does not support item assignment
八、 chr( K ) 与 ord( c )python 2.4.2以前
将编码K 转为字符,K的范围是 0 ~ 255
取单个字符的编码, 返回值的范围: 0 ~ 255python 3.0
将编码K 转为字符,K的范围是 0 ~ 65535
取单个字符的编码, 返回值的范围: 0 ~ 65535
九、 除法运算符python 2.4.2以前
python 3.0
10 / 3 结果为 3.3335
10 // 3 结果为 3
十、字节数组对象 --- 新增(一) 初始化
a = bytearray(
# a 是一个由十个字节组成的数组,其每个元素是一个字节,类型借用 int
# 此时,每个元素初始值为 0(二) 字节数组 是可变的
a = bytearray(
# 可以用赋值语句更改其元素,但所赋的值必须在 0 ~ 255 之间(三)
字节数组的切片仍是字节数组(四)
字符串转化为字节数组
#coding=gbk
b = s.encode( "gbk")
# 先将字符串按某种&GBK&编码方式转化为 bytes
c = bytearray( b )
#再将 bytes 转化为 字节数组
也可以写作
c = bytearray( "你好", "gbk") (五)
字节数组转化为字符串
c = bytearray( 4 )
c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68
s = c.decode( "gbk" )
print ( s )
# 应显示: ABCD
(六) 字节数组可用于写入文本文件#coding=gbkf = open("c:\\1234.txt", "wb")s = "张三李四abcd1234"# -------------------------------# 在 python2.4 中我们可以这样写:# f.write( s )# 但在 python 3.0中会引发异常# -------------------------------b = s.encode("gbk")f.write( b )c=bytearray( "王五","gbk")f.write( c )f.close()input("?") ================================
阅读(...) 评论()您所在的位置: &
3.4 结构化程序示例(1)
3.4 结构化程序示例(1)
周伟、宗杰
机械工业出版社
《Python开发技术详解》共27章,第3章详细介绍了Python中的控制语句、循环语句以及一些习惯用法,结合实例讲解了Python进行结构化编程的要点。本节说的是结构化程序示例。
3.4 结构化程序示例
本节将结合结构化程序设计的思路,讲解使用Python实现冒泡排序的方法。冒泡排序将使用前面讲解的条件判断和循环语句等知识。冒泡排序是数据结构中的一种排序算法,学过数据结构课程的读者应该不陌生。
冒泡排序的基本思想是,将需要排序的元素看作是一个个“气泡”,最小的“气泡”最快浮出水面,排在前面。较小的“气泡”排在第二个位置,依次类推。冒泡排序需要对数列循环若干次, 例如数列中有i个元素。第一遍循环,自底向上检查一遍这个数列,比较相邻的两个元素。如果较小的元素在数列的下面,把较小的元素排在前面。依次比较之后,就把最大的元素置于底部了,第二遍循环就不需要比较最后一个元素了。依次类推,第n遍循环只需要从第一个元素开始,比较i-n次。经过i-1遍的处理后,数列就排序完成了。
假设有一个数列\[23, 12, 9, 15, 6\],这个数列的排序过程如图3-2所示。
在实现中将用到xrange()。前面提到了range()函数生成迭代集合。此外,还可以使用xrange()。xrange()的用法和range()相同,xrange()的声明如下所示:xrange(\[start,\]&stop\[,&step\])&-&&xrange&object&
xrange是一个类,而且返回的是一个xrange对象。使用xrange()进行遍历,每次遍历只返回一个值。range()返回的是一个列表,一次性计算并返回所有的值。因此,xrange()的执行效率要高于range()。
【责任编辑: TEL:(010)】&&&&&&
关于&&&&&&的更多文章
在内容上,《Android系统源代码情景分析(修订版)(含CD光盘1张
本书描述了黑客用默默无闻的行动为数字世界照亮了一条道路的故事。
讲师: 15人学习过讲师: 36人学习过讲师: 15人学习过
本书共4部分,首先简要介绍了开发相关的基础知识,然
本书将帮助你理解和使用PostgreSQL这一开源数据库系统
本书由业界最先进的动画库Velocity.js的作者所著,书
本书内容包括:
● 框架的总览:SQL Server 2005的功能是如何集成在一起的,以及这些功能对于用户的意义。
51CTO旗下网站}

我要回帖

更多关于 xrange与range的区别 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信