新手程序员在这里.自学Python.关于Stackoverflow的第一个问题.
我正在尝试根据用户选择的价格,评级和烹饪类型来编写推荐餐厅的计划.为实现这一目标,该计划构建了三个数据结构:[我还处于中间阶段]
# Initiating the data structures
name_rating = {}
price_name = {}
cuisine_name = {}
Run Code Online (Sandbox Code Playgroud)
数据来自restaurants.txt,格式如下:
#Rest name
#Rest Rating
#Rest Price range
#Rest Cuisine type
#
#Rest2 name
Run Code Online (Sandbox Code Playgroud)
等等
以下函数仅返回所需行的字符串
# 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)]
Run Code Online (Sandbox Code Playgroud)
增加5,分别获取每家餐厅的数据.
fname = 'restaurants.txt'
fhand = open(fname)
Run Code Online (Sandbox Code Playgroud)
以下返回名称字典:评级
# 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
Run Code Online (Sandbox Code Playgroud)
以下返回价格字典:名称
# 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
Run Code Online (Sandbox Code Playgroud)
调用函数
print pricename()
print namerate()
Run Code Online (Sandbox Code Playgroud)
问题:当我调用函数时,为什么只有我首先调用的函数才能成功?第二个词典仍然是空的.如果我单独调用它们,则构建数据结构.如果我同时打电话,只有第一个成功.
ps我确信我可以更快地做到这一切,但是现在我正在尝试自己这样做,所以有些看似多余或不必要.请多多包涵 :)
您可以使用方法将文件位置设置为重新开始seek(请参阅文档):
f = open("test.txt")
for i in f:
print(i)
# Print:
# This is a test first line
# This is a test second line
for i in f:
print(i)
# Prints nothig
f.seek(0) # set position to the beginning
for i in f:
print(i)
# Print:
# This is a test first line
# This is a test second line
Run Code Online (Sandbox Code Playgroud)