Py学习  »  Python

如何在Python中构造具有多个特性的元素

Artemyx • 5 年前 • 1385 次点击  

如果我有一组元素(a,B,C,D…),它们都有两个或多个特征(每一个都有颜色、形状等等…),那么我如何构造一个结构,以便我可以轻松地要求所有绿色元素或所有圆形元素的列表?
我想用字典,但不知道这是否是最有效的方法。我知道每个对象的每个特性的值永远不会改变。没有很多特征,但是有很多对象。

这是一套的样子:

test = {'ob1': {'color': ['green'], 
                'shape': 'round'},
        'ob2': {'color': ['red'], 
                'shape': 'round'},
        'ob3': {'color': ['green', 'yellow'], 
                'shape': 'cubic'}
        }

我想要一个简单的方法来获得包含[ob1,ob2]的列表,如果我想获得所有的绿色对象。但同时,我仍然希望能够很容易地找到给定对象的属性(例如,我想知道obj1是什么颜色和形状)。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49566
 
1385 次点击  
文章 [ 5 ]  |  最新文章 5 年前
Rifat Alptekin Çetin
Reply   •   1 楼
Rifat Alptekin Çetin    6 年前

您可以使用类:

class element:
    def __init__(self,shape,color):
        self.shape=shape
        self.color=color

查询功能:

def query(data,shape=None,color=None):
     if shape:
         data=[x for x in data if x.shape==shape]
     if color:
         data=[x for x in data if x.color==color]
     return data

使用:

red_circle=element("circle","red")
red_square=element("square","red")
blue_circle=element("circle","blue")
blue_square=element("square","blue")

data=[red_circle,red_square,blue_circle,blue_square]
qdata=query(data,color="blue")

for x in qdata:
    print("shape: {} - color: {}".format(x.shape,x.color))
holdenweb
Reply   •   2 楼
holdenweb    6 年前

通常情况下,问题会显示非工作代码,以获得有助于工作的答案。

一种方法是使用一个字典,它的键是特征,每个值是另一个字典,它的键是每个属性的可能值。它的值将是一组具有属性的给定值的元素。

所有的绿色元素

elements['colour']['green']

所有的元素都是

elements['shape']['circle']

通过使用set操作,可以很容易地找到圆形的绿色对象,例如

elements['colour']['green'].intersection(elements['shape']['circle'])
chitown88
Reply   •   3 楼
chitown88    6 年前

在我看来,熊猫是一种很好的方式。但你当然可以用字典:

elements = ['A', 'B', 'C', 'D']
colors = ['red','red', 'blue', 'red']
shapes = ['square', 'circle', 'circle', 'triangle']


dict1 = { element: {'color':colors[index], 'shape':shapes[index]} for index,element in enumerate(elements)}


def find_keys(keyword):
    result = []
    for key, val in dict1.items():
        for k, v in val.items():
            if v == keyword:
                result.append(key)
    return result

print (find_keys('red'))

输出:

 print (find_keys('red'))
['A', 'B', 'D']

print (find_keys('circle')) 
['B', 'C']
Polkaguy6000
Reply   •   4 楼
Polkaguy6000    6 年前

我不知道你的数据是什么样子的,所以很难推荐,但这看起来像是 pandas . Pandas可以创建一个基本上像电子表格一样的数据框。导入数据后,可以根据特征进行筛选和排序。不过,字典在大多数情况下都是好的。见 pandas documentation .

balderman
Reply   •   5 楼
balderman    6 年前

您可以使用namedtuple这是一种有效的数据格式。

from collections import namedtuple

Element = namedtuple('Element', 'color size id name')

ELEMENTS_DB = {'e1':Element('green', 12, 34, 'jack'),
               'e2':Element('blue', 132, 334, 'dan'),
               'e3':Element('green', 142, 434, 'ben')}

# get green elements
green_elements = [e for e in ELEMENTS_DB.values() if e.color == 'green']
print(green_elements)
# get 'e3' 
print(ELEMENTS_DB['e3'])

输出:

[Element(color='green', size=12, id=34, name='jack'), Element(color='green', 
  size=142, id=434, name='ben')]
Element(color='green', size=142, id=434, name='ben')