如何制作元组作为衍生物的结构或层次结构?

问题描述:

我想在Python中创建一个结构或相关的层次结构,例如:名称xxxx附加到列表中,并且在xxxx下存储多个“ID”?并且在搜索它将返回的ID的情况下,该ID已经被存储在其中xxxx如何制作元组作为衍生物的结构或层次结构?

以使其更清晰,为xxxxyyyy

xxxx - |- 112  yyyy - |- 123 
     |- 113    |- 124 
     |- 114    |- 125 

,并在寻找这些ID的它会返回该集团其所属,也就是说,如果我搜索114,它会返回它属于yyyy

class Post: 
    ID   = [] 
    incoming_data = '' 
    Buff   = 0 
    IP   = [] 
    contact_info = '' 

    def Map(self, object): 
     object.contact_info = object.IP + object.ID 
     print object.contact_info 

obj1 = Post() 
obj1.incoming = '112113114115116' 
obj1.IP.append('xxx.xxx.xxx.xxx') 

for x in range(1,6): #seperates it into sets of 3 digit numbers. 
    obj1.ID.append(obj1.incoming_data[(3 * x) - 3: 3 * x]) 

obj1.Map(obj1)  #Prints the concatenated value of the both the strings. 

我已经到了这里,它把它作为一个字符串,但我应该使用元组呢?我有点新,而且我只盯了几个小时,任何帮助表示赞赏。我想知道可能的方法。

本次输出:

['xxx.xxx.xxx.xxx', '112', '113', '114', '115', '116'] 
+0

你的意思是元组。另外,我认为你正在寻找字典。 –

+0

@COLDSPEED关于如何使用它的任何细节我的情况? – Jack

+0

'{'xxxx':[112,113,114],'yyyy':[123,124,125]}' –

你可以使用字典(这是在c类似于哈希表)。请记住,字典提供O(1)访问指定密钥的值。因此,在你的情况下,值(113,114等)在它们之间都是不同的,你可以使用它们作为密钥,并通过它们以相应的名称(例如xxxx,yyyy等等)访问。 。)

>>> d = { 
...  112 : 'xxxx', 
...  113 : 'xxxx', 
...  114 : 'xxxx', 
...  123 : 'yyyy', 
...  124 : 'yyyy', 
...  125 : 'yyyy', 
... } 
>>> print d[114] 
xxxx 

更新

要存储一个键就可以使用list多个值。

>>> d = { 
...  112 : ['xxxx'], 
...  113 : ['xxxx'], 
...  114 : ['xxxx'], 
...  123 : ['yyyy'], 
...  124 : ['yyyy'], 
...  125 : ['yyyy'], 
...  } 
>>> 
>>> d[114].append('zzzz') 
>>> d.items() 
[(112, ['xxxx']), (113, ['xxxx']), (114, ['xxxx', 'zzzz']), (123, ['yyyy']), (124, ['yyyy']), (125, ['yyyy'])] 
>>> d[114] 
['xxxx', 'zzzz'] 

第二方式(使用collections.defaultdict)第一方式

>>> from collections import defaultdict 
>>> 
>>> l = [(114, 'xxxx'), (113, 'yyyy'), (123, 'xxxx'), (114, 'yyyy'), (125, 'xxxx')] 
>>> d = defaultdict(list) 
>>> for k, v in l: d[k].append(v) 
... 
>>> d.items() 
[(113, ['yyyy']), (114, ['xxxx', 'yyyy']), (123, ['xxxx']), (125, ['xxxx'])] 
>>> d[114] 
['xxxx', 'yyyy'] 
+0

这个想法似乎很好,但是如何将值附加到它们? – Jack

+0

@Jack更新了答案! – coder

IP = "xxx.xxx.xxx.xxx" 
data = (112, 113, 114, 115, 116) 

mydict = {} 
mydict[IP] = data 

print mydict 

hunt = 114 

if hunt in mydict[IP]: 
    print("{} is in {}".format(hunt, IP)) 

下面是关于字典教程:https://docs.python.org/3.6/tutorial/datastructures.html#dictionaries

+0

这也是一个好主意。 – Jack