如何将类对象列表转换为其属性列表 [英] How to convert lists of class objects to a list of their attributes

查看:89
本文介绍了如何将类对象列表转换为其属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们!因此,我最近开始学习python类和对象。
例如,我有以下字符串列表:

guys! So I recently started learning about python classes and objects. For instance, I have a following list of strings:

alist = ["Four", "Three", "Five", "One", "Two"]

其中哪一个与一类数字相当有:

Which is comparable to a class of Numbers I have:

class Numbers(object):
   One=1
   Two=2
   Three=3
   Four=4
   Five=5

我怎么转换 alist 进入

alist = [4, 3, 5, 1, 2]

基于上述类别?

我最初的想法是创建一个新的(空)列表并使用 for循环添加相应的对象值(例如 Numbers.One )通过 alist 进入空白列表。但是我不确定这是否是最有效的解决方案。

My initial thought was to create a new (empty) list and use a for loop that adds the corresponding object value (e.g. Numbers.One) to the empty list as it goes through alist. But I'm unsure whether that'd be the most efficient solution.

因此,我想知道是否存在使用Python类/继承完成此任务的更简单方法。

Therefore, I was wondering if there was a simpler way of completing this task using Python Classes / Inheritance.

我希望有人能帮助我并向我解释哪种方法会更好,为什么!

I hope someone can help me and explain to me what way would work better and why!

谢谢!

推荐答案

虽然我完全同意将 dict 用于数字更简单明了,但向您展示枚举的方式,因为您的课程涉及魔术数字和使用枚举的有效用例。

While I totally agree that using a dict for Numbers would be easier and straight forward, but showing you the Enum way as your class involves magic numbers and sort of a valid use case for using enums.

使用 Enum 的类似实现为:

from enum import Enum

class Numbers(Enum): 
    One = 1 
    Two = 2 
    Three = 3 
    Four = 4 
    Five = 5 

然后您可以使用 getattr Numbers。< attr> .value 来获取常数:

Then you can use getattr and Numbers.<attr>.value to get the constant numbers:

In [592]: alist = ["Four", "Three", "Five", "One", "Two"]                                                                                                                                                   

In [593]: [getattr(Numbers, n).value for n in alist]                                                                                                                                                        
Out[593]: [4, 3, 5, 1, 2]






基于评论进行编辑:

如果您想从电话号码列表中找回姓名,

If you want to get the names back from a number list:

In [952]: l = [4, 3, 5, 1, 2]                                                                                                                                                                               

In [953]: [Numbers(num).name for num in l]                                                                                                                                                                  
Out[953]: ['Four', 'Three', 'Five', 'One', 'Two']

这篇关于如何将类对象列表转换为其属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆