我在这里遇到了这个功能.
我对这将如何实现感到困惑 - 如何key通过cmp_to_key知道给定元素的"位置"而不检查给定元素与其他感兴趣元素的比较来生成函数?
我一直在尝试创建一个dict继承的子类,UserDict.DictMixin它支持不可散列的密钥.性能不是问题.不幸的是,Python DictMixin通过尝试从子类创建一个dict对象来实现一些功能.我自己可以实现这些,但我坚持下去__cmp__.
我找不到__cmp__dict类内置使用的逻辑的简洁描述.
我正在尝试使用排序对象列表
my_list.sort(key=operator.attrgetter(attr_name))
但如果有任何列表项attr = None而不是attr = 'whatever',
然后我得到了 TypeError: unorderable types: NoneType() < str()
在Py2中,这不是问题.我如何在Py3中处理这个?
蟒3.X的sorted()功能不能依赖于异质序列进行排序,因为大多数对不同类型的是unorderable(数字类型,如int,float,decimal.Decimal等是一个例外):
Python 3.4.2 (default, Oct 8 2014, 08:07:42)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> sorted(["one", 2.3, "four", -5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: float() < str()
Run Code Online (Sandbox Code Playgroud)
相比之下,没有自然顺序的对象之间的比较是任意的,但在Python 2.x中是一致的,所以sorted()工作:
Python 2.7.8 (default, Aug 8 2014, 14:55:30)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> sorted(["one", 2.3, "four", -5]) …Run Code Online (Sandbox Code Playgroud) 追溯ValueError: cannot convert float NaN to integer我发现的那条线:
max('a', 5)
max(5, 'a')
Run Code Online (Sandbox Code Playgroud)
将返回a而不是5.
在上面的例子中,我使用了示例字符串,a但在我的实际情况中,字符串是a NaN(未能收敛的拟合过程的结果).
这种行为背后的理由是什么?为什么python不会自动识别出那里有一个字符串并且它应该返回该数字?
更好奇的是,min() 没有工作,因为预期:
min('a', 5)
min(5, 'a')
Run Code Online (Sandbox Code Playgroud)
回报5.
我使用了许多类似json的词组.pprint构建它们很方便.有没有办法使pprint输出中的所有整数以十六进制而不是十进制打印?
例如,而不是:
{66: 'far',
99: 'Bottles of the beer on the wall',
'12': 4277009102,
'boo': 21,
'pprint': [16, 32, 48, 64, 80, 96, 112, 128]}
Run Code Online (Sandbox Code Playgroud)
我宁愿看到:
{0x42: 'far',
0x63: 'Bottles of the beer on the wall',
'12': 0xFEEDFACE,
'boo': 0x15,
'pprint': [0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80]}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过定制PrettyPrinter,但无济于事,我能够导致上述情况,PrettyPrinter.format()处理整数似乎只适用于某些整数:
class MyPrettyPrinter(PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, int):
return '0x{:X}'.format(object), True, False
return super().format(object, context, maxlevels, level)
Run Code Online (Sandbox Code Playgroud)
以上课程产生
{0x42: 'far',
0x63: …Run Code Online (Sandbox Code Playgroud) 我有一个带有字典的列表,在其中按不同的值对它们进行排序。我正在使用以下代码行:
def orderBy(self, col, dir, objlist):
if dir == 'asc':
sorted_objects = sorted(objlist, key=lambda k: k[col])
else:
sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True)
return sorted_objects
Run Code Online (Sandbox Code Playgroud)
现在的问题是,当我尝试排序时,偶尔会出现空值或空字符串,然后一切都崩溃了。
我不确定,但是我认为这是引发的异常:不可排序的类型:NoneType()<NoneType()。当我尝试排序的列上没有值时,就会发生这种情况。对于空字符串值,尽管它们在列表中排在最后,但它可以工作,但我希望它们排在最后。
我怎么解决这个问题?
python ×7
python-3.x ×3
sorting ×3
python-2.x ×2
algorithm ×1
cmp ×1
hex ×1
list ×1
max ×1
min ×1
null ×1
pprint ×1
python-2to3 ×1