How to compare the sizes of certain members of multiple objects in Python?
学习ing
学习ing 2017-06-13 09:24:48
0
2
762

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
学习ing

reply all(2)
曾经蜡笔没有小新

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
给我你的怀抱

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template