Java's TreeSet equivalent in Python?

后端 未结 6 1892
悲&欢浪女
悲&欢浪女 2020-12-30 22:32

I recently came across some Java code that simply put some strings into a Java TreeSet, implemented a distance based comparator for it, and then made its merry way into the

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 23:05

    The Python 2.7 docs for collections.OrderedDict has a link to a OrderedDict recipe that runs on Python 2.4 or better.

    Edit: In regard to sorting: Use key= rather than cmp=. It tends to lead to faster code and moreover, the cmp= keyword has been eliminated in Python3.

    d={5:6,7:8,100:101,1:2,3:4}
    print(d.items())
    # [(1, 2), (3, 4), (100, 101), (5, 6), (7, 8)]
    

    The code you posted for mycmp doesn't make it clear what you want passed as x1. Below, I assume x1 is supposed to be the value in each key-value pair. If so, you could do something like this:

    length=4
    print(sorted(d.items(),key=lambda item: abs(item[1]-length) ))
    # [(3, 4), (1, 2), (5, 6), (7, 8), (100, 101)]
    

    key=... is passed a function, lambda item: abs(item[1]-length). For each item in d.items(), the lambda function returns the number abs(item[1]-length). This number acts as proxy for the item as far as sorting is concerned. See this essay for more information on sorting idioms in Python.

    PS. len is a Python builtin function. So as to not clobber that len, I've changed the variable name to length.

提交回复
热议问题