Python sorting()

huangapple go评论74阅读模式
英文:

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, &quot;toyota&quot;),
                    Car(4, &quot;BMW&quot;),
                    Car(2, &quot;Chevloret&quot;),
                    Car(1,&quot;Ford&quot;)]
        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 
&gt; TypeError: &#39;Car&#39; 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, &quot;toyota&quot;), Car(4, &quot;BMW&quot;), Car(2, &quot;Chevloret&quot;), Car(1, &quot;Ford&quot;)]
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

huangapple
  • 本文由 发表于 2023年7月12日 23:37:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定