Java TreeSet在Python中等效吗?

时间:2010-04-26 01:26:52

标签: java python data-structures treeset

我最近遇到了一些Java代码,只是简单地将一些字符串放入Java TreeSet中,为它实现了一个基于距离的比较器,然后以快乐的方式进入日落计算给定分数以解决给定问题。

我的问题,

  • 是否有可用于Python的等效数据结构?

    • Java树集看起来基本上是一个有序字典,可以使用某种比较器来实现这种排序。
  • 我看到OrderedDict有PEP for Py3K,但我使用的是2.6.x.有一堆有序的dict实现 - 特别是可以推荐的任何人?

PS,只是添加 - 我可以可能导入DictMixin或UserDict并实现我自己的排序/有序字典,并通过比较器函数实现 - 但这似乎有点矫枉过正。

感谢。


更新。谢谢你的回答。为了详细说明,我可以说我有一个定义的比较函数,(给定一个特定的值ln),

def mycmp(x1, y1, ln):
  a = abs(x1-ln)
  b = abs(y1-ln)
  if a<b:
    return -1
  elif a>b:
    return 1
  else:
    return 0

我有点不确定如何将它整合到有序字典link given here..中给出的顺序中。

类似的东西,

OrderedDict(sorted(d.items(), cmp=mycmp(len)))

欢迎提出意见。

6 个答案:

答案 0 :(得分:5)

Python 2.7 docs for collections.OrderedDict包含一个在Python 2.4或更高版本上运行的OrderedDict recipe的链接。

修改:关于排序:使用key=而不是cmp=。它往往导致faster code,而且,Python3中已消除cmp=关键字。

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

您为mycmp发布的代码并未明确说明您想要传递的内容为x1。下面,我假设x1应该是每个键值对中的。如果是这样,你可以这样做:

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

key=...传递了一个函数lambda item: abs(item[1]-length)。 对于item中的每个d.items(),lambda函数返回数字abs(item[1]-length)。就排序而言,此数字充当项目的代理。有关在Python中排序习语的更多信息,请参阅this essay

PS。 len是一个Python内置函数。为了不破坏len,我已将变量名称更改为length

答案 1 :(得分:3)

我最近使用bisect模块为Python实现了TreeSet。

https://github.com/fukatani/TreeSet

它的用法类似于Java的Treeset。

离。

from treeset import TreeSet
ts = TreeSet([3,7,2,7,1,3])
print(ts)
>>> [1, 2, 3, 7]

ts.add(4)
print(ts)
>>> [1, 2, 3, 4, 7]

ts.remove(7)
print(ts)
>>> [1, 2, 3, 4]

print(ts[2])
>>> 3

答案 2 :(得分:2)

我需要查看一些示例数据,但如果您只是尝试进行加权排序,那么内置的python sorted()可以通过两种方式完成。

有序的元组和key()函数:

def cost_per_page(book):
    title, pagecount, cost = book
    return float(cost)/pagecount

booklist = [
        ("Grey's Anatomy", 3000, 200),
        ('The Hobbit', 300, 7.25),
        ('Moby Dick', 4000, 4.75),
]
for book in sorted(booklist, key=cost_per_page):
    print book

或带有__cmp__运算符的类。

class Book(object):
    def __init__(self, title, pagecount, cost):
        self.title = title
        self.pagecount = pagecount
        self.cost = cost
    def pagecost(self):
        return float(self.cost)/self.pagecount
    def __cmp__(self, other):
        'only comparable with other books'
        return cmp(self.pagecost(), other.pagecost())
    def __str__(self):
        return str((self.title, self.pagecount, self.cost))

booklist = [
        Book("Grey's Anatomy", 3000, 200),
        Book('The Hobbit', 300, 7.25),
        Book('Moby Dick', 4000, 4.75),
]
for book in sorted(booklist):
    print book

这两个都返回相同的输出:

('Moby Dick', 4000, 4.75)
('The Hobbit', 300, 7.25)
("Grey's Anatomy", 3000, 200)

答案 3 :(得分:0)

1。 我不认为python有内置的Sorted集。 这样的事情怎么样?

letters = ['w', 'Z', 'Q', 'B', 'C', 'A']
  for l in sorted(set(letters)):
     print l

2.Java TreeSet是一个名为SortedSet的抽象实现。基本类型将按自然顺序排序。TreeSet实例使用compareTo(或compare)方法执行所有键比较。因此,您的自定义键应实现正确的compareTo

答案 4 :(得分:0)

如果您想要的是一个总是按排序顺序迭代的集合,那么这可能会让您大部分时间:

def invalidate_sorted(f):
    def wrapper(self, *args, **kwargs):
        self._sort_cache = None
        return f(self, *args, **kwargs)
    return wrapper

class SortedSet(set):
    _sort_cache = None

    _invalidate_sort_methods = """
        add clear difference_update discard intersection_update
        symmetric_difference_update pop remove update
        __iand__ __ior__ __isub__ __ixor__
        """.split()

    def __iter__(self):
        if not self._sort_cache:
            self._sort_cache = sorted(set.__iter__(self))
        for item in self._sort_cache:
            yield item

    def __repr__(self):
        return '%s(%r)' % (type(self).__name__, list(self))

    for methodname in _invalidate_sort_methods:
        locals()[methodname] = invalidate_sorted(getattr(set, methodname))

答案 5 :(得分:-3)

当您使用Java树集时:

 import java.util.*;
class Main{
         public static void main(String args[])
          {
             TreeSet<Integer> tr=new TreeSet<>();
             tr.add(3);
             tr.add(5);
             tr.add(7);
             tr.add(6);
             tr.add(3);
             tr.add(8);

             Iterator itr=tr.iterator();
             for(int i=0;i<tr.size();i++)
            {
               System.out.print(tr.get(i)+" ");  
            } 
          }
     }

    >>>> **3 5 6 7 8**


  same AS in python:
from treeset import TreeSet
tr = TreeSet([1,2,2,7,4,3])
print(tr)
>>> [1, 2, 3, 4,7] 
相关问题