Python 非基类型集合?
我正在学习 python,我对列表、元组、字典、集合等不同数据结构的用途有点困惑。
例如,假设汽车是由品牌、型号、马力定义的
我希望有一个汽车集合,我可以
- 按马力进行排序,或
- 按型号进行品牌比较(以删除重复项),
- 只需使用 for 语句进行迭代即可
- 按型号删除元素
实现此目的的最佳方法是什么?
- 我是否需要创建一个 Car 类,并重新定义一些函数(如 C 中的运算符 == 和 >),然后将它们存储在列表中
- 或者我应该将它们制作为字典,还是自己重新定义字典?然后让 python 为我对它们进行排序(我认为这对于操作员模块是可能的,如果我错了请纠正我)
- 还有其他吗?
I'm learning python, and I'm a bit confused about which the purpose of the different data structures like list, tuples, dictionaries, sets.
For example, let's say cars are defined by Brand,Model,Horsepower
I wish to have a collection of cars on which I could
- sort by Horsepower, or brand
- compare by model (to erase duplicates)
- iterate simply with a for statement
- remove elements by model
What would be the best way to achieve this?
- Do I need to create a class Car, and redefine some functions (like operators == and > in C), then store them in a list
- Or should I make them a dictionary, or redefine a dictionary myself ? and then have python sort them for me (I think this is possible with the operator module, correct me if I'm wrong)
- something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像大多数事情一样,有不止一种可能的方法。
使用类
最巧妙的可能是创建一个
Car
类。您不需要重新定义运算符——只需一些属性和构造函数。然后,如果您想按型号进行比较:
如果您有一个
Car
对象列表,并想按马力对它们进行排序:使用字典
当然,因为您将对该类执行所有操作正在存储一组属性,您也可以只使用字典来代替 - 您只是失去了刚性(并获得了一些灵活性)。模仿上面的代码,但使用字典:
然后,如果您想按型号进行比较:
如果您有一个
Car
对象列表,并且想按马力对它们进行排序:Like most things, there's more than one possible approach.
Using a class
The neatest would probably be to make a
Car
class. You don't need to redefine operators - just have some properties and a constructor.Then, if you wanted to compare by model:
If you had a list of
Car
objects, and wanted to sort them by horsepower:Using a dict
Of course, since all you'd be doing with the class is storing a set of properties, you could also just use dicts instead - you just lose the rigidity (and gain some flexibility). To mimic the code above, but with dicts:
Then, if you wanted to compare by model:
If you had a list of
Car
objects, and wanted to sort them by horsepower:我会用一个类 Car 和一个 dict(model:Car) 来存储不同的汽车。
I would do it with a class Car and a dict(model:Car) store different cars.