Sorting a List of Objects by an Attribute of the ObjectsCase-Insensitively

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jason

    Sorting a List of Objects by an Attribute of the ObjectsCase-Insensitively

    Hi folks--

    Basically, I have a pressing need for a combination of 5.2 "Sorting a
    List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects
    by an Attribute of the Objects" from the Python Cookbook.

    My first guess isn't working:

    import operator
    def sort_by_attr(se q, attr):
    key=operator.at trgetter(attr)
    key=str.lower
    return sorted(seq, key)

    ....would much appreciate any guidance!
  • Paddy

    #2
    Re: Sorting a List of Objects by an Attribute of the ObjectsCase-Insensitively

    On Apr 9, 4:04 am, Jason <elgrandchig... @gmail.comwrote :
    Hi folks--
    >
    Basically, I have a pressing need for a combination of 5.2 "Sorting a
    List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects
    by an Attribute of the Objects" from the Python Cookbook.
    >
    My first guess isn't working:
    >
    import operator
    def sort_by_attr(se q, attr):
    key=operator.at trgetter(attr)
    key=str.lower
    return sorted(seq, key)
    >
    ...would much appreciate any guidance!
    HiJason,
    Try key= lambda x: x.attr.lower()
    The above should calculate the key only once for the items to be
    sorted rather than using cmp which calculates more than that.

    - Paddy.

    Comment

    • Jason

      #3
      Re: Sorting a List of Objects by an Attribute of the ObjectsCase-Insensitively

      Thanks so much everyone! That works great, & (presumably) is way
      faster than the way I was doing it--

      Comment

      Working...