我注意到Python允许我这样做:
>>> {1: "foo"} < {2: "bar"}
True
它让我可以对列表、数据队列等做同样的事情。当<
应用于Python语言中的字典时,它的语义是什么?
一般来说,我在哪里可以找到任何给定类型的集合的<
语义?在大多数情况下,它似乎在文档中找不到。例如:
>>> help(dict.__cmp__)
Help on wrapper_descriptor:
__cmp__(...)
x.__cmp__(y) <==> cmp(x,y)
>>> help(cmp)
Help on built-in function cmp in module __builtin__:
cmp(...)
cmp(x, y) -> integer
Return negative if x<y, zero if x==y, positive if x>y.
我这样问是因为我有一个(int, dict)
形式的元组列表。我想根据第一个元素对这个数组进行排序,但是如果第一个元素对于两个项目是相等的,那么我并不关心第二个元素。我想知道在这种情况下,myArray.sort()
是否会做一些复杂的事情,包括递归遍历字典,还是只返回一个任意值。
发布于 2018-08-09 23:11:58
我喜欢@thefourtheye的答案。
它是用python编写的,可以这样解释:
def dict_compare(a, b):
if len(a) != len(b): # STEP 1: compare by length
return -1 if len(a) < len(b) else 1
res = 0
akey, aval = characterize(a, b) # Find first k, v that a[k] != b[k]
bkey, bval = characterize(b, a)
if akey is None: # if no difference
return 0
if bkey is not None: # STEP 2: compare by key
res = cmp(akey, bkey)
if res == 0 and bval is not None: # STEP 3: compare by value
res = cmp(aval, bval)
return res
其中characterize
函数类似于:
def characterize(a, b):
"""Find the first k that a[k] != b[k]"""
akey, aval = None, None
for k, v in a.items():
if akey < k:
continue
if (k not in b) or (a != b[k]):
akey, aval = k, v
return akey, aval
https://stackoverflow.com/questions/23192163
复制相似问题