[英]Python: Use sets in conjunction with dictionaries
我這里有這種方法,它以字典的形式生成有向圖,其中鍵的值是鍵指向的節點,即{'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
我的問題是,如何使用帶有字典的集合來防止將與有關密鑰相同的值添加到密鑰中?
這是我重新編碼圖形構建器的方法; 使用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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.