第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Python:結(jié)合使用集和字典

Python:結(jié)合使用集和字典

千萬里不及你 2021-03-05 21:22:20
我在這里使用此方法以字典的形式生成有向圖,其中鍵的值是鍵指向的節(jié)點(diǎn),即{'stack':['over','flow']},stack指向結(jié)束并流動(dòng)...def generateGraph(fileName):    heroDict = {}    graph = {}    with open(fileName) as inFile:        for line in inFile:#go through each line            name_comic = line.rstrip().replace('"', '').split('\t') #split into list with name and comic book as strings            if name_comic[1] in heroDict: #if the comic book is already in the dictionary                heroDict[name_comic[1]] += [name_comic[0]] #add the hero into the comic's list of heroes            else:                heroDict.update({name_comic[1]: [name_comic[0]]}) # update dictionary with name and comic book    for i in heroDict.values():        for j in i:            if graph.has_key(j):                tempDict = copy.deepcopy(i)                tempDict.remove(j)                heroList = tempDict                graph[j] += heroList            else:                tempDict = copy.deepcopy(i)                tempDict.remove(j)                heroList = tempDict                graph[j] = heroList        print graph #<========== the graph has duplicates, ie, values that are the same as their keys are present    return graph我的問題是,如何實(shí)現(xiàn)帶有字典的集合的使用,以防止將與所討論的鍵相同的值添加到鍵中?
查看完整描述

1 回答

?
犯罪嫌疑人X

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊

這是我重新編碼您的圖形生成器的方法;使用csv模塊和collections.defaultdict類使代碼大大更易讀:


import csv

from collections import defaultdict


def generateGraph(fileName):

    heroDict = defaultdict(list)


    with open(fileName, 'rb') as inFile:

        reader = csv.reader(inFile, delimiter='\t')

        for row in reader:

            name, comic = row[:2]

            heroDict[comic].append(name)


    graph = defaultdict(list)

    for names in heroDict.itervalues():

        for name in names:

            graph[name].extend(n for n in names if n != name)

    print graph

    return graph

此處無需使用集。注意,我使用了更有意義的變量名。盡量避免i和j除非它們是整數(shù)索引。


查看完整回答
反對(duì) 回復(fù) 2021-03-26
  • 1 回答
  • 0 關(guān)注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)