对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 __cmp__():
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.name <s.name:
return -1
elif self.name >s.name:
return 1
else:
return 0
上述 Student 类实现了__cmp__()方法,__cmp__用实例自身self和传入的实例 s 进行比较,如果 self 应该排在前面,就返回 -1,如果 s 应该排在前面,就返回1,如果两者相当,返回 0。
Student类实现了按name进行排序:
>>>L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77)]
>>>print sorted(L)
[(Alice: 77), (Bob: 88), (Tim: 99)]
注意: 如果list不仅仅包含 Student 类,则 __cmp__ 可能会报错:
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
print sorted(L)
请思考如何解决。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if(self.score<s.score):
return 1
if(self.score>s.score):
return -1
if(self.score==s.score):
if(self.name>s.name):
return 1
if(self.name<s.name):
return -1
return 0
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
designer.exe 无法打开背景python 3.8 按照pip install pyqt5和pip install pyqt5-tools完成安装后,进入..PythonLibsite-packagespyqt5_toolsQtbin目录打开designer.exe报错如下:
解决方案
将以下目录中的两个dll文件 …PythonLibsite-packagespyqt5_toolsQtpluginsplatforms
拷贝覆盖到 …PythonLibsite-packagespyqt5_toolsQtbinplatforms 目录下,即可正常打开designer.exe
PS:下面看下Qt-Designer打不开的问题
安装Qt后双击桌面的Designer没有反应,解决办法就是将安装路径里的qwebengineview.dll文件后缀名加个".bak"。
相关学习推荐:python教程
以上就是小编分享的关于解决python下QT5 Designer打不开的问题的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!
from random import randomimport os
class Filehandle(object):
def __init__(self):
pass
def handle_file(self, file_path):
# To get the content of the txt file
file_content = open(file_path, "r")
# create a list container to save the new content
f_list = []
# handle the old content to produce the new content
# you can change the handle code on your own
for i in file_content:
i_name = i.split("[")[0]
i_value_new = str(random()) + " " + str(random())
i_new = i_name + "[" + i_value_new + "]"
f_list.append(i_new)
# close the file
file_content.close()
# open the file to wride mode
f_w = open(file_path, "w")
# file the file with the new content
for i in f_list:
f_w.write(i + os.linesep)
# close the file
f_w.close()
if __name__ == "__main__":
path = "/Users/mymachine/myProject/file.txt"
fh = Filehandle()
fh.handle_file(path)
# go to check the txt file which is already changed to new content.