用对象填充列表并排序(新手)

2024-04-25 20:03:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,所以请原谅我使用了错误的术语:)

我想要几个“对象”的列表,每个对象都有相同的数值属性(a、B、C)。然后,该列表应按属性A的值排序

在Java中,我定义一个类,将我的属性作为成员,实现Sortable来比较a,将它们全部放入某种类型的列表中,让Collections.sort对我的列表进行排序。在

结果应该是这样的:

A   B   C
1   2   3
1   2   4
2   5   1
3   1   1

在Python中执行类似操作的最佳方法是什么?在


Tags: 对象类型列表属性定义排序错误成员
3条回答

对不起,如果我误解了你的问题。我不太明白。在

所以,我假设你想按列排序

假设x是二维数组

>>> x=[[1, 2, 3], [1, 2, 4], [2, 5, 1], [3, 1, 1]]
>>> x
[[1, 2, 3], [1, 2, 4], [2, 5, 1], [3, 1, 1]]

下面是一种使用itemgetter按每列进行排序的方法

^{pr2}$

如果您想要就地排序,请按x.sort(key=itemgetter(0))

考虑使用namedtuple来创建对象。(看看is-there-a-tuple-data-structure-in-python。)

collections.namedtuple(typename, field_names[, verbose])

Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful repr() method which lists the tuple contents in a name=value format.

具有A B C字段名的简单交互式会话。排序很简单 key=lambda o:o.A

>>> import collections
>>> mob=collections.namedtuple('myobj',('A','B','C'))
>>> mlist = [mob(3,1,1), mob(1,2,3), mob(1,2,4), mob(2,5,1)]
>>> mlist
[myobj(A=3, B=1, C=1), myobj(A=1, B=2, C=3), myobj(A=1, B=2, C=4), myobj(A=2, B=5, C=1)]
>>> for x in sorted(mlist,key=lambda o:o.A):
...     print x
...     
myobj(A=1, B=2, C=3)
myobj(A=1, B=2, C=4)
myobj(A=2, B=5, C=1)
myobj(A=3, B=1, C=1)
>>> 
class myclass(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __repr__(self):
        return "(a=%s, b=%s, c=%s)" % (self.a, self.b, self.c)

>>> obj1 = myclass(1, 2, 3)
>>> obj2 = myclass(1, 2, 4)
>>> obj3 = myclass(2, 5, 1)
>>> obj4 = myclass(3, 1, 1)

>>> print sorted([obj1, obj2, obj3, obj4], key=lambda o: o.a)
[(a=1, b=2, c=3), (a=1, b=2, c=4), (a=2, b=5, c=1), (a=3, b=1, c=1)]

相关问题 更多 >