[英]Index class as list and as dictionary
给出list
和dict
的类行为是一种好习惯吗? 这允许一个用户通过instance[str]
和instance[int]
两者访问项目。 例如:
class Population(object):
def __init__(self, populationlist):
self.population = populationlist
def __getitem__(self, value):
if isinstance(value, str):
index = self.get_names().index(value)
return self.population[ index ]
elif isinstance(value, int:
return self.population[value]
def get_names(self):
return [ ind.name for ind in self.population ]
class Individual(object):
def __init__(self, name):
self.name=name
my_pop = Population( [ Individual(name) for name in [ 'a', 'b', 'c', 'd' ] ] )
my_pop['c']
>> 'c'
my_pop[2]
>> 'c'
显然,您可以创建一个为您处理所有这些问题的类, 但 不会对其进行优化 。 您应该做的是使用Python的OrderedDict
来创建具有顺序的高效字典。
您问这是否是一个好习惯 ,答案很明确: 否 。
Python模块this
提到了一些好的做法:
>>> import this
这里有四行内容适用:
Explicit is better than implicit.
:
您将字符串索引隐式转换为数字索引!
Special cases aren't special enough to break the rules.
当您输入字符串索引时,这显然是一种特殊情况。 有什么特别之处?
In the face of ambiguity, refuse the temptation to guess.
这几乎就像特殊情况一样。 您猜测没有人会输入等效的第二项(是否返回第一或第二或最后一个?),而且没人会使用整数作为名称。
There should be one-- and preferably only one --obvious way to do it.
我认为这是相当主观的,但我将其解释为“一个功能应具有其他功能无法实现的一个目的”。 您的__getitem__
有两个目的。 拥有方法"find_by_name"
和一个方法"find_by_index"
并不是问题。
但是,还包括一些建设性的反馈:看起来好像您想要一个表格结构。 如果是这样,您应该考虑熊猫或某些数据库,也许是sqllite
?
只是为了展示pandas
如何解决这个问题:
>>> import pandas as pd
>>> df = pd.DataFrame({'name': ['a', 'b', 'c', 'd']})
>>> print(df)
name
0 a
1 b
2 c
3 d
>>> print(df[df['name'] == 'a']) # index by name
name
0 a
>>> print(df.iloc[[0]]) # index by index
name
0 a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.