我试图将一些代码从Python 2移植到Python 3.它是丑陋的东西,但我试图让Python 3的结果与Python 2的结果一样可能。我有类似的代码如下:在Python中使用Python 2 Dict比较3
import json
# Read a list of json dictionaries by line from file.
objs = []
with open('data.txt') as fptr:
for line in fptr:
objs.append(json.loads(line))
# Give the dictionaries a reliable order.
objs = sorted(objs)
# Do something externally visible with each dictionary:
for obj in objs:
do_stuff(obj)
当我端口的代码在Python 2到Python 3,我得到一个错误:
TypeError: unorderable types: dict() < dict()
所以我改变了排序行这样的:
objs = sorted(objs, key=id)
但是Python 2和Python 3的
之间还改变了字典的排序是有办法REPLI在Python 3中指定Python 2比较逻辑?简单地说,之前使用了id
,并且在Python版本之间不可靠?
您是否需要在3中复制Python 2的逻辑,或者您是否只需要*一些*这两者之间的一致性排序? – DSM 2014-09-04 21:44:01
'如果你只关心关键比较,'sorted(objs,key = sorted)'有效。 (并在2和3中实现它,真的没有办法匹配3的任意排序) – roippi 2014-09-04 21:49:10
我想复制顺序。 – 2014-09-04 21:49:26