簡體   English   中英

使用python從字典中提取客戶端服務器的順序

[英]Extracting order of client server from a dictionary using python

我有一個像下面這樣的字典,例如,對於第一個項目,意味着5是2的客戶。在最后一個項目中,如您所見,2是4的客戶,而4也是項目3的客戶。

customer_provider_dic= {'2':['5'],'1':['2'],'3':['4'],'4':['2']}

我正在嘗試提取這些項目的所有客戶鏈。 輸出將如下所示:

[2,5]
[1,2,5]
[3,4,2,5]
[4,2,5]

我真的很困惑如何提取這些鏈。 關於流程圖或步驟的任何建議。

首先,如果所有列表中都包含一個項目,那么這是一個可行的解決方案。

def simple_chain(graph, key):
    chain = [key]
    while True:
        lst = graph.get(key)
        if lst is None:
            # There's nothing left to add to the chain
            break
        key = lst[0]
        if key in chain:
            # We've found a loop
            break
        chain.append(key)
    return chain

customer_provider = {
    '2': ['5'], '1': ['2'], '3': ['4'], '4': ['2'],
}

data = customer_provider
for k in data:
    print(simple_chain(data, k))

輸出

['2', '5']
['1', '2', '5']
['3', '4', '2', '5']
['4', '2', '5']

一般的解決方案要難一些。 我們可以使用遞歸生成器創建所有鏈。 下面的代碼可以工作,但是效率不高,因為它多次創建相同的子鏈。

基本策略與以前的版本相似,但是我們需要遍歷每個列表中的所有鍵,並為每個列表創建新的鏈。

要完全理解此代碼的工作方式,您需要熟悉遞歸和Python 生成器 您可能還會發現此頁面有幫助: 了解Python中的生成器 在線上也有各種Python生成器教程。

def make_chains(graph, key, chain):
    ''' Generate all chains in graph that start at key.
        Stop a chain when graph[key] doesn't exist, or if
        a loop is encountered.
    '''
    lst = graph.get(key)
    if lst is None:
        yield chain
        return
    for k in lst:
        if k in chain:
            # End this chain here because there's a loop
            yield chain
        else:
            # Add k to the end of this chain and
            # recurse to continue the chain
            yield from make_chains(graph, k, chain + [k])

customer_provider = {
    '2': ['5'], '1': ['2'], '3': ['4'], '4': ['2'],
}

pm_data = {
    '2': ['5'], '1': ['2'], '3': ['4', '6'], 
    '4': ['2'], '6': ['1', '5'],
}

#data = customer_provider
data = pm_data

for k in data:
    for chain in make_chains(data, k, [k]):
        print(chain)

如果我們使用data = customer_provider運行該代碼,它將產生與先前版本相同的輸出。 這是使用data = pm_data運行時的輸出。

['2', '5']
['1', '2', '5']
['3', '4', '2', '5']
['3', '6', '1', '2', '5']
['3', '6', '5']
['4', '2', '5']
['6', '1', '2', '5']
['6', '5']

語法的yield from是Python 3的功能。 要在Python 2上運行此代碼,請更改

yield from make_chains(graph, k, chain + [k])

for ch in make_chains(graph, k, chain + [k]):
    yield ch 

之前PYTHON 3.6 dict不保留鍵的插入順序,所以for k in data可以在的鍵環data以任何順序。 輸出列表仍然是正確的。 您可能希望將該循環替換為

for k in sorted(data):

使鏈條井然有序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM