Python sorting()

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

Python sorting()

问题

如何对这种嵌套列表进行排序,而不将列表拆分为单独的部分?

  1. class Car:
  2. def __init__(self, carid, carname):
  3. self.carid = id
  4. self.carname = name
  5. def __str__(self):
  6. return str(self.__dict__)
  7. def cars():
  8. car_car = [Car(3, "toyota"),
  9. Car(4, "BMW"),
  10. Car(2, "Chevrolet"),
  11. Car(1, "Ford")]
  12. car_car.sort(key=lambda v: (v.carid, v.carname)) ### 这里
  13. return car_car
  14. 我想使用 .sort 选项按字母顺序对数据进行排序而不拆分列表
  15. 我得到了
  16. > TypeError: 'Car' object is not subscriptable error
  17. 使用 sorted() .sort() 也会出现此错误
  18. <details>
  19. <summary>英文:</summary>
  20. How to sort this type of nested list without splitting the list into separate?
  21. class Car:
  22. def __init__(self, carid, carname):
  23. self.carid = id
  24. self.carname = name
  25. def __str__(self):
  26. return str(self.__dict__)
  27. def cars():
  28. car_car = [ Car(3, &quot;toyota&quot;),
  29. Car(4, &quot;BMW&quot;),
  30. Car(2, &quot;Chevloret&quot;),
  31. Car(1,&quot;Ford&quot;)]
  32. cars.sort(key=lambda v: (v[0], v[1])) ### here
  33. return car_car
  34. I want to sort the data alphabetically using the .sort option without splitting that list
  35. I got
  36. &gt; TypeError: &#39;Car&#39; object is not subscriptable error
  37. with sorted() and .sort()
  38. </details>
  39. # 答案1
  40. **得分**: 1
  41. ```python
  42. class Car:
  43. def __init__(self, carid, carname):
  44. self.carid = carid
  45. self.carname = carname
  46. def __str__(self):
  47. return str(self.__dict__)
  48. def cars():
  49. car_car = [Car(3, "toyota"), Car(4, "BMW"), Car(2, "Chevrolet"), Car(1, "Ford")]
  50. car_car.sort(key=lambda car: car.carname) # 根据carname属性对列表进行排序
  51. return car_car
  52. sorted_cars = cars()
  53. for car in sorted_cars:
  54. print(car)

要对Car对象的列表进行排序,而不将其拆分为单独的元素,可以使用sorted()函数和自定义的键函数。该代码根据每个Car对象的carname属性按字母顺序对car_car列表进行排序。

英文:
  1. class Car:
  2. def __init__(self, carid, carname):
  3. self.carid = carid
  4. self.carname = carname
  5. def __str__(self):
  6. return str(self.__dict__)
  7. def cars():
  8. car_car = [Car(3, &quot;toyota&quot;), Car(4, &quot;BMW&quot;), Car(2, &quot;Chevloret&quot;), Car(1, &quot;Ford&quot;)]
  9. car_car.sort(key=lambda car: car.carname) # Sort by carname attribute
  10. return car_car
  11. sorted_cars = cars()
  12. for car in sorted_cars:
  13. 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:

确定