2017-08-03 67 views
-2
{'a':[0,1], 'b':[1,2], 'c':[2,3], 'd':[10,11], 'e':[11,12], 'f':[12,13]}  

目標是在字典中查找連接的值。 那麼,結果將是,順序並不重要:根據字典中的值內容查找連接的鍵

{1:['a','b','c'], 2:['d','e','f']}  

我試過循環與許多條件和遞歸。 但只是更困惑。

循環示例,它的工作原理,但返回連接值的副本:

def used(a, data): 
    try: 
     for key in data.keys(): 
      if a in data[key]: 
       return True 
      else: 
       return False 
    except: 
     return False 

def is_connected(a_data, b_data): 
    if [a for a in a_data if a in b_data]: 
     return True 
    else: 
     return False 

collection = {} 
key = 1 
get_init = True 
for i in edges: 
    for e in edges: 
     if used(e, collection): 
      continue 
     if get_init: 
      init = e 
      chain = [] 
      chain.append(init) 
      get_init = False 
      continue 
     else: 
      pass 
     if is_connected(init, e): 
      chain.append(e) 
      init = e 
     else: 
      continue 
    collection[key] = chain 
    key += 1 
    get_init = True 

遞歸,這並不在所有的工作:

def recursion(a, data): 
     for d in data: 
      if is_connected(a, d): 
       print d 
       a = d 
       recursion(a, data) 
+0

字典是沒有順序的。 https://stackoverflow.com/questions/6083531/order-of-keys-in-python-dictionary – 16num

回答

0

遞歸做的工作。 爲了達到這個結果,我改變了一個條件。 並從列表開始,而不是字典。

def set_chains(name): 
    region = {} 
    edges_init = cmds.ls(sl=True, fl=True) 
    edges_split = split_edges_on_chains(edges_init) 

    for i, edges in edges_split.iteritems(): 
     cmds.select(edges) 
     vtxs = cmds.ls(cmds.polyListComponentConversion(tv=True), fl=True) 
     region[str(i)] = [v.split('.')[-1] for v in vtxs] 

    self.edges[name] = region 

def is_connected(a, b): 
    a_vtxs = cmds.ls(cmds.polyListComponentConversion(a, tv=True), fl=True) 
    b_vtxs = cmds.ls(cmds.polyListComponentConversion(b, tv=True), fl=True) 
    shared_vtxs = [a for a in a_vtxs if a in b_vtxs] 
    if shared_vtxs: 
     return True 
    else: 
     return False 

def get_edge_chain(chain, data): 
    for c in chain: 
     connected = [d for d in data if is_connected(c, d) and d not in chain] 
     if not connected: 
      continue 
     chain.append(connected[0]) 
     data.remove(connected[0]) 
     return get_edge_chain(chain, data) 
    del data[0] 
    return chain 

def split_edges_on_chains(data):  
    chains = {} 
    iter = 0 
    while data: 
     chains[iter] = get_edge_chain([data[0]], data) 
     iter += 1 
    return chains 

data = ['a','b','c','d','e','f'] 
split_edges_on_chains(data) 

我找到數據的每一個項目的屬性 同時調用一個函數

is_connected()