python3.x与python2.x的一些区别

今日在学习python过程中,学的是python2.x,本机环境装的是python3.x,所以总是有一些出错,特来总结一下:

python2.x:

#---1、输出语句---
print ‘hello world’              #直接输出

#---2、range()函数---
print range(1,10);               #range()函数和filter()一样
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9] 

#---3、filter()函数,与range()函数一样,在python3中输出要加list()迭代显示---
'''
请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
'''
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
print filter(is_sqr, range(1,101));
>>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#---4、reduce()函数---
def prod(x,y):
    return x * y
print reduce(prod, [2, 4, 5, 7, 12])
>>> 3360

#---5、定制除法函数__div__---
def __div__(self, r):            #除法__div__
    return Rational(self.p * r.q, self.q * r.p)

#---6、排序函数sorted()---
'''
请先看下面一个例题:
对字符串排序时,有时候忽略大小写排序更符合习惯。请利用sorted()高阶函数,实现忽略大小写排序的算法。
输入:['bob', 'about', 'Zoo', 'Credit']
输出:['about', 'bob', 'Credit', 'Zoo']
'''
def cmp_ignore_case(x):
    return x.upper()
 
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)

python3.x:

#---1、输出语句---
print (‘hello world’)             #加括号输出

#---2、range()函数---
print (range(1,100));             #range()函数和filter()一样
>>> range(1, 100)
print (list(range(1,10)));
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]   #range()函数正确的结果

#---3、filter()函数,与range()函数一样,在python3中输出要加list()迭代显示---
'''
请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
'''
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
print ( list(filter(is_sqr, list(range(1,101)))) );
>>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#---4、reduce()函数---
from functools import reduce
def prod(x,y):
    return x * y
print ( reduce(prod, [2, 4, 5, 7, 12]) );
>>> 3360

#---5、排序函数sorted()---
'''
请先看下面一个例题:
对字符串排序时,有时候忽略大小写排序更符合习惯。请利用sorted()高阶函数,实现忽略大小写排序的算法。
输入:['bob', 'about', 'Zoo', 'Credit']
输出:['about', 'bob', 'Credit', 'Zoo']
'''
def cmp_ignore_case(x):
    return x.upper()
print ( sorted(['bob', 'about', 'Zoo', 'Credit'], key = cmp_ignore_case) );
>>> ['about', 'bob', 'Credit', 'Zoo']
print ( sorted(['bob', 'about', 'Zoo', 'Credit'], key = lambda x: x.upper()) );
>>> ['about', 'bob', 'Credit', 'Zoo']
'''
python2和python3中sorted()函数的区别详见:https://blog.csdn.net/qq_37811638/article/details/83058907
'''

#---6、定制除法函数__div__---
'''
python3中除法得的结果是浮点数
'''
def __truediv__(self, r):         #除法__truediv__
    return Rational(self.p * r.q, self.q * r.p)

爬虫相关:

Python2.x  Python3.x
urllib2.urlopen()   urllib.request.urlopen()
urllib2.Request() urllib.request.Request()
htmllib.HTMLParser  html.parser.HTMLParse
httplib http.client
cookielib http.cookiejar
urllib.urlencode() urllib.parse.urlencode()

猜你喜欢

转载自blog.csdn.net/qq_37811638/article/details/83108629