在Python中创建多个数据结构(dicts)

时间:2014-06-17 22:22:57

标签: python dictionary

新手程序员在这里。自学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。我确信我可以更快地做到这一切,但是现在我正在尝试自己这样做,所以有些可能看起来多余或不必要。请耐心等待:))

1 个答案:

答案 0 :(得分:1)

您可以使用seek方法将文件位置重新设置为开头(请参阅docs):

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