-2

How to sort this type of nested list without splitting the list into separate?

class Car:

    def __init__(self, carid, carname):
        self.carid = id
        self.carname = name

    def __str__(self):
        return str(self.__dict__)

def cars():
    car_car = [ Car(3, "toyota"),
                Car(4, "BMW"),
                Car(2, "Chevloret"),
                Car(1,"Ford")]
    cars.sort(key=lambda v: (v[0], v[1])) ### here

    return car_car

I want to sort the data alphabetically using the .sort option without splitting that list

I got

TypeError: 'Car' object is not subscriptable error

with sorted() and .sort()

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • Your lambda applies to things like tuples and lists, which have elements that can be accessed via `[0]`, `[1]`, etc., where `[0]` and `[1]` are *subscripts*. Python classes aren't automatically like that. `carid` and `carname` aren't the 1st and 2nd elements of a `Car` object, so `Car` is not subscriptable. (Perhaps you are thinking of a [named tuple](https://docs.python.org/3/library/collections.html#collections.namedtuple), where attributes are accessible via both a name and a subscript.) – jjramsey Jul 12 '23 at 15:56

1 Answers1

1
class Car:
    def __init__(self, carid, carname):
        self.carid = carid
        self.carname = carname
    
    def __str__(self):
        return str(self.__dict__)

def cars():
    car_car = [Car(3, "toyota"), Car(4, "BMW"), Car(2, "Chevloret"), Car(1, "Ford")]
    car_car.sort(key=lambda car: car.carname)  # Sort by carname attribute
    return car_car

sorted_cars = cars()
for car in sorted_cars:
    print(car)

To sort the list of Car objects without splitting it into separate elements, you can use the sorted() function with a custom key function. The code sorts the car_car list alphabetically by the carname attribute of each Car object

Golam Moula
  • 83
  • 2
  • 7