我是一名初学者程序员,正在自学Python。这是我在StackOverflow上的第一个问题。
我正在尝试编写一个程序,根据用户选择的价格、评分和菜系类型来推荐餐厅。为了实现这个目标,程序构建了三个数据结构:[我仍然处于中级阶段]
# Initiating the data structures
name_rating = {}
price_name = {}
cuisine_name = {}
数据来自于格式化为以下形式的 restaurants.txt 文件:
#Rest name
#Rest Rating
#Rest Price range
#Rest Cuisine type
#
#Rest2 name
以下函数仅返回所需行的字符串。
# The get_line function returns the 'line' at pos (starting at 0)
def get_line(pos):
fname = 'restaurants.txt'
fhand = open(fname)
for x, line in enumerate(fhand):
line = line.rstrip()
if not pos == x: continue
return line
# Locating the pos's of name, rate, price & cuisine type for each restaurant
# Assumes uniform txt file formatting and unchanged data set
name_pos = [x for x in range(0,84,5)]
rate_pos = [x for x in range(1,84,5)]
price_pos = [x for x in range(2,84,5)]
cuis_pos = [x for x in range(3,84,5)]
每次增加5以便为每个餐厅单独获取数据。
fname = 'restaurants.txt'
fhand = open(fname)
以下返回一个名称:评分的字典。
# Builds the name_rating data structure (dict)
def namerate():
for x, line in enumerate(fhand):
line = line.rstrip()
for n, r in zip(name_pos, rate_pos):
if not n == x: continue
name_rating[line] = name_rating.get(line, get_line(r))
return name_rating
以下代码返回一个价格:名称的字典。
# Builds the price_name data structure (dict)
def pricename():
for x, line in enumerate(fhand):
line = line.rstrip()
for p, n in zip(price_pos, name_pos):
if not p == x: continue
price_name[line] = price_name.get(line, get_line(n))
return price_name
调用函数
print pricename()
print namerate()
问题:当我调用函数时,为什么只有第一个被调用的成功了?第二个字典保持为空。如果我分别调用它们,数据结构就会建立。如果我同时调用两个,只有第一个成功。
p.s. 我相信我可以更快地完成所有这些工作,但现在我正在尝试自己做一些,因此有些可能显得冗余或不必要。请耐心等待 :)