英文:
Python sorting()
问题
如何对这种嵌套列表进行排序,而不将列表拆分为单独的部分?
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, "Chevrolet"),
Car(1, "Ford")]
car_car.sort(key=lambda v: (v.carid, v.carname)) ### 这里
return car_car
我想使用 .sort 选项按字母顺序对数据进行排序,而不拆分列表
我得到了
> TypeError: 'Car' object is not subscriptable error
使用 sorted() 和 .sort() 也会出现此错误。
<details>
<summary>英文:</summary>
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()
</details>
# 答案1
**得分**: 1
```python
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, "Chevrolet"), Car(1, "Ford")]
car_car.sort(key=lambda car: car.carname) # 根据carname属性对列表进行排序
return car_car
sorted_cars = cars()
for car in sorted_cars:
print(car)
要对Car对象的列表进行排序,而不将其拆分为单独的元素,可以使用sorted()函数和自定义的键函数。该代码根据每个Car对象的carname属性按字母顺序对car_car列表进行排序。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论