首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将文件行与python中的字符串进行比较,以及不一致

将文件行与python中的字符串进行比较,以及不一致
EN

Stack Overflow用户
提问于 2016-08-19 01:29:03
回答 1查看 14关注 0票数 0

这段代码应该按照执行顺序做一些重要的事情:

1.打开并读取文件"Goods“

2.将文件"Goods“中的任意一行分配给字典"goods”

3.遍历if块,该代码块将为字典"cost“分配一个随机值,前提是goodsx等于要比较的字符串。

4.打印“货物”和“成本”

5.重复步骤2-4,再重复2次。

代码语言:javascript
复制
from random import randint

print("You search for things to buy in the market, and find:")
f = open('Goods', 'r') #Opens file "Goods"
lines = f.readlines() #Loads all lines from "Goods"
goods = {1:"", 2:"", 3:""}
cost = {1:"", 2:"", 3:""}
x = 0
while x < 3:
    x += 1
    goods[x] = lines[randint(0, 41)].strip()

#Checks to see if goods[x] is equal to the string on the right, if it is, it assigns cost[x] to a random integer
    if goods[x] == "Lumber":
        cost[x] = randint(2, 3)
    elif goods[x] == "Rum":
        cost[x] == randint(3, 4)
    elif goods[x] == "Spices":
        cost[x] = randint(4, 5)
    elif goods[x] == "Fruit":
        cost[x] == randint(2, 4)
    elif goods[x] == "Opium":
        cost[x] == randint(1, 5)


    findings = '%s for %s gold.' %(goods[x], cost[x])
    print(findings)

这段代码的问题是,当goodsx等于: Rum、Fruit或Opium时,字典:“cost”不能从if块中获得赋值。

有人能告诉我这是怎么回事吗?

The file "Goods"

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-19 01:43:11

你的问题是你使用的是两个等号。cost[x] == randint(3, 4)你只需要使用一个。希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39024200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档