gpt4 book ai didi

python - 从 python 类中的文件构建字典

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:57 25 4
gpt4 key购买 nike

我正在尝试构建一个类,该类从一个文件构建一个字典,该字典采用列表中的第一项并使其成为键和列表值中的其余项目。所以最后当我这样调用它时

neighbors=Neighbors(FileName.txt)

但是当我说

neighbors['New York']

它不返回该键的值

class Neighbors(dict):

def __init__(self, fname):
states=[]
states1=[]
states2=[]
self.fname=open(fname)
for line in self.fname:
line=line[:-1]
states.append(line)
for line in states:
states1.append(line.split(','))
for line in states1:
item=[x.strip(' ') for x in line]
states2.append(item)
a=dict([(t[0],t[1:]) for t in states2])

neighbors = Neighbors("us_states_adjacency.txt")
print neighbors

最佳答案

def neighbors(fname):
def make_line(adjacent_cities):
line = [city.strip() for city in adjacent_cities.split(",")]
return line[0],line[1:]
return dict(map(make_line,open(fname)))

我想我会这样做......

没有理由为此使用类......你只需要一本字典

但是如果你真的希望它成为一个类

class Neighbors(dict):
def __init__(self,fname):
def make_line(adjacent_cities):
line = [city.strip() for city in adjacent_cities.split(",")]
return line[0],line[1:]
dict.__init__(self,map(make_line,open(fname)))

如果你不想改进原来的类而只想修复它,你只需要调用 super inits 方法

class Neighbors(dict):

def __init__(self, fname):
states=[]
states1=[]
states2=[]
self.fname=open(fname)
for line in self.fname:
line=line[:-1]
states.append(line)
for line in states:
states1.append(line.split(','))
for line in states1:
item=[x.strip(' ') for x in line]
states2.append(item)
dict.__init__(self,[(t[0],t[1:]) for t in states2]) # call super constructor on our dict ...

这是一个更简单的类,它覆盖 dict ...

class dummy(dict):
def __init__(self,initializer):
dict.__init__(self,initializer)

d = dummy([('a',2),('b',4)])
print d['a']
print d['c']

关于python - 从 python 类中的文件构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23000797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com