簡體   English   中英

如何從字典中的每個鍵中檢索多個最大值

[英]How to retrieve multiple maximum values from each keys in a dictionary

如何從字典中的每個鍵中檢索多個最大值(或前 N 個值)。

communities_dict = {1: "A","B","C","D","E","F","G","CB" 
                    2: "H","I","J","K","L","M","N","XY" 
                    3: "O","P","Q","R","S","T","U","GT"
                    4: "V","W","X","Y","Z","AB" "HH","FF", 
                    5: "CD","EF","GH","IJ","KL","HG","FR","RR"}
# load the network graph 

G = nx.read_adjlist("./data/networkgraph.csv", delimiter = ',')

# cluster the network graph

partition = community.best_partition(G)

# Get a set of the communities

communities = set(partition.values())
    
# Create a dictionary mapping community number to nodes within that community

communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}
    
# Filter that dictionary to map community to the node of highest degree within the community

highest_degree = {k: max(v, key=lambda x: G.degree(x)) for k, v in communities_dict.items()}

這是我從highest_degree 得到的字典是:

1: "A"
2: "I"
3: "Q"
4: "AB" 
5: "CD" 

但理想情況下,我希望每個鍵的度數最高的前 3 個節點而不是只有一個。

1: "A","B","C"
2: "I", "J","K"
3: "Q","P","Q"
4: "V","W","X"
5: "CD", "EF","GH"
                

由於您想要具有最高程度的3個節點,您可以使用sorted然后使用[-3:]對新列表進行切片以獲取最后 3 個元素。 在您的示例中,這看起來像:

highest_degree = {k: sorted(v, key=G.degree)[-3:] for k, v in communities_dict.items()}

對於每個鍵的多個值,您必須使用 [] 作為您的值。 您的代碼有一些語法錯誤,例如您沒有使用逗號將先前的值與下一個鍵分開。 你的代碼必須是這樣的:

'''

    dict = {1: ["A","B","C","D","E","F","G","CB"],
            2: ["H","I","J","K","L","M","N","XY"],
            3: ["O","P","Q","R","S","T","U","GT"],
            4: ["V","W","X","Y","Z","AB" "HH","FF"], 
            5: ["CD","EF","GH","IJ","KL","HG","FR","RR"]}   

'''

暫無
暫無

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

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