找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1574|回复: 1

[求助] 新人不知道怎么loop使字典的值改变

2

主题

3

帖子

3

积分

贫民

积分
3
刘越阳 发表于 2018-1-19 08:57:01 | 显示全部楼层 |阅读模式
import urllib.request #this loads a library you will need. Put this line at the top of your file.
def readfile():
    case =[]
    response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/treasure.txt")
    html = response.readline().decode('utf-8')
    while len(html) > 0:
        html = response.readline().decode('utf-8')
        case.append(html.strip("\n"))
    return case


def process_list(case):
    for i in range(len(case)-1):
        if case[0] in ["0","1", "2", "3", "4", "5", "6", "7", "8", "9"]:
            case = int(case)
    case.remove('') # I don't know why but it dose have a '' at the end of the list
return case


def put_in_bag(thing, bag = {}):
    bag[thing] = 1
    return bag


def ask_for_input(case):
    print("Please choose a number from {} to {}".format(0, len(case)-1))
    user_input = int(input("Enter here: "))
    return user_input


def what_behind(tidy_case, user_input):
    thing = tidy_case[user_input]
    return thing


def increment(bag, thing,):
    bag[thing] += 1
    return bag


def main():
    signal = True
case = readfile()
    tidy_case = process_list(case)
    print(tidy_case)
    while signal:
        user_input = ask_for_input(tidy_case)
        thing = what_behind(tidy_case, user_input)
        try:
            while type(thing) == int:
                thing = what_behind(tidy_case, thing)

            bag = put_in_bag(thing)
            bag[thing] += 1

            print("Wow, you get a {}, the {} is put in your backpack.".format(thing, thing))

        except IndexError:
            print("You are out of the map now!!")
            print("All you belongs and points are zero now")
            signal = False
        finally:
            print("here is item {}, and number {}".format(thing, bag[thing]))
            print(bag)


main()
这个大概就是玩家随意输入一个数字,然后到达指定位置,若果有宝藏,东西将放入背包,如果重复是一件宝藏,数量则增加。但我现在每次loop完,会被bag = put_in_bag(thing)重置背包,不知道该怎么改了
回复

使用道具 举报

2

主题

3

帖子

3

积分

贫民

积分
3
刘越阳  楼主| 发表于 2018-1-20 03:46:14 | 显示全部楼层
抱歉之前的代码可能有点冗长,意思没有表达清楚,我简单重写了一个问题部分
def user():
    answer = input("what you want to put in your bag? ")
    return answer

def put(answer,bag ={}):
    bag[answer] = 0
    return bag

def main():
    signal =True
    while signal:
        answer = user()
        bag = put(answer)
        if answer in bag:
            bag[answer] += 1
            print(bag)

main()
就是这样的一个代码,我想要实现每次用户输入同一个字符的时候,相对应键的值+1, 但是因为每次在循环体内bag = put(answer),值都会被重置,请问怎么解决呢
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表