Java's TreeSet equivalent in Python?

后端 未结 6 1858
悲&欢浪女
悲&欢浪女 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:12

    I'd need to see some example data, but if you're just trying to do a weighted sort, then the builtin python sorted() can do it, two ways.

    With well ordered tuples and a key() function:

    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
    

    or with a class with a __cmp__ operator.

    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
    

    Both of these return the same output:

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

提交回复
热议问题