search

Home  >  Q&A  >  body text

How to compare the sizes of certain members of multiple objects in Python?

There are multiple objects of the same type, a b c
Each object has the same integer attribute a.click

Now we need to sort according to the numerical value of click (there may be duplicates),

Then take out the other member data in the object according to the sorting position of click

I have been thinking about it for a long time, how to implement it

学习ing学习ing2728 days ago775

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-13 09:26:48

    Is this so?

    # coding: utf8
    
    class A():
        def __init__(self):
            self.click = 0
    
    
    a = A()
    a.click = 4
    a.test = 'I am a'
    
    b = A()
    b.click = 1
    b.test = 'I am b'
    
    c = A()
    c.click = 2
    c.test = 'I am c'
    
    for i in sorted([a, b, c], key=lambda x: x.click, reverse=True):
        print i.test
        
    # 输出(根据click的值从小到大输出test属性)
    I am b
    I am c
    I am a

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-13 09:26:48

    Write an example:

    #!/usr/bin/python3
    
    
    class Class:
    
        def __init__(self, key, value):
            self.key, self.value = key, value
    
    
    def get_values(*args):
        return [o.value for o in sorted(args, key=lambda o: o.key)]
    
    
    print(
        get_values(
            Class(3, 1),
            Class(1, 2),
            Class(2, 3)
        )
    )
    
    # Output: [2, 3, 1]

    Is this what you mean

    reply
    0
  • Cancelreply