为了账号安全,请及时绑定邮箱和手机立即绑定

Python:结合使用集和字典

Python:结合使用集和字典

千万里不及你 2021-03-05 21:22:20
我在这里使用此方法以字典的形式生成有向图,其中键的值是键指向的节点,即{'stack':['over','flow']},stack指向结束并流动...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我的问题是,如何实现带有字典的集合的使用,以防止将与所讨论的键相同的值添加到键中?
查看完整描述

1 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

这是我重新编码您的图形生成器的方法;使用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除非它们是整数索引。


查看完整回答
反对 回复 2021-03-26
  • 1 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号