Skip to main content
 首页 » 编程设计

python之使用 Python 数据结构表示这一点的最佳方式

2025年05月04日18leader

  <specification>  
    <propertyName> string </propertyName> 
    <value>  
      <number>  
        <value> anyNumberHere </value> 
      </number> 
      <text>  
        <value> anyTextHere </value> 
      </text> 
      <URL>  
        <value> anyURIHere </value> 
      </URL> 
    </value> 
    <!-- ... 1 or more value nodes here ... --> 
  </specification> 
  <!-- ... 1 or more specification nodes here ... --> 

我需要为 API 构建此请求,用户将在其中传递这些值。那么,最好的表示方式应该是什么,以便该方法的用户可以轻松地将相应的值传递给操作?

我在想:

字典列表:

[specification1, specification2, specification3] 

地点:

specification1= [value1, value2] 

地点:

value1 = {number:anyNumberHere, text:anyTextHere, URL:anyURIHere} 
value2 = {number:anyNumberHere, text:anyTextHere, URL:anyURIHere} 

但是,我无法容纳:<propertyName>这里。有什么建议吗?

此外,这听起来很复杂。我们可以像在 Java 中那样进行对象封装吗?我明白,我们可以,但我很好奇,python 中推荐的方式是什么?

My logic for now, suggestions (incorrect due to propertyName): 
    #specification is a List of List of Dicts 
    for spec in specification: 
        specification_elem = etree.SubElement(root, "specification") 
        propertyName_elem = etree.SubElement(specification_elem,"propertyName") 
        propertyName_elem.text = spec_propertyName 
 
        for value in spec: 
            value_elem = etree.SubElement(specification_elem, "value") 
            for key in value: 
                key_elem = etree.SubElement(value_elem, key) 
                keyValue_elem = etree.SubElement(key_elem, "value") 
                keyValue_elem.text = value[key] 

在这里,我将通过spec_propertyName ,作为差异参数。因此,用户将通过:specification and spec_propertyName

请您参考如下方法:

规范对象列表如何,每个对象都有一个 property_name 和一个 value 字典列表? (values 可以是对象列表而不是字典。)

例如:

class Value(object): 
    def __init__(self, 
                 number=None, 
                 text=None, 
                 url=None): 
        self.number = number 
        self.text = text 
        self.url = url 
 
class Specification(object): 
    def __init__(self, propertyName): 
        self.propertyName = propertyName 
        self.values = [] 
 
spec1 = Specification("Spec1") 
spec1.values = [Value(number=3, 
                      url="http://www.google.com"), 
                Value(text="Hello, World!", 
                      url="http://www.jasonfruit.com")] 
 
spec2 = Specification("Spec2") 
spec2.values = [Value(number=27, 
                      text="I can haz cheezburger?", 
                      url="http://stackoverflow.com"), 
                Value(text="Running out of ideas.", 
                      url="http://news.google.com")]