【问题标题】:My program is printing value following the order of my .txt file and I don't want that to happen我的程序正在按照我的 .txt 文件的顺序打印值,我不希望这种情况发生
【发布时间】:2023-03-04 10:41:01
【问题描述】:

我想提示用户从文本文件(键)中输入特定数据,以便我的字典可以为它们中的每一个提供值。

它是这样工作的:

fin=open('\\python34\\lib\\toys.txt')
toys = {}

for word in fin:
    x=fin.readline()
    x = word.replace("\n",",").split(",")
    a = x[0]
    b=x[1]
    toys[a]=str(b)
    i = input("Please enter the code:")
    if i in toys:
        print(i," is the code for a= ", toys[i],)
    else:
        print('Try again')
    if i == 'quit':
        break

但如果我从列表中输入随机键,它会打印“重试”。 (如下:

D1,霸王龙

D2,阿帕塔龙

D3,迅猛龙

D4,三角龙

D5,翼手龙

T1,柴油电动

T2,蒸汽机

T3,厢式车

T4,油罐车

T5,守车

B1,棒球

B2、篮球

B3,足球

B4、垒球

B5,网球

B6,排球

B7,橄榄球

B8,板球

B9,药球

但如果我按顺序执行它就可以了。我怎样才能修复这个程序,以便我可以随时输入任何键,它仍然会打印相应的值?

【问题讨论】:

  • for word in fin: 后跟x=fin.readline():您似乎单步执行文件中的行(for 循环),然后立即读取文件的另一行。然后你扔掉下一个 readline() 的结果。对吗?
  • 也许做一些标准调试是个好主意,并在循环中打印出 word、x、a 和 b 以查看发生了什么。
  • 是的。 x=fin.readline() 读取每一行,然后 ` x = word.replace("\n",",").split(",") ` 将键与我的字典的值分开。 @Evert
  • @Evert 我尝试在循环外打印出每一个,并且效果很好。我不明白问题是什么,但谢谢!!
  • 回复:您的第一条评论:可能存在误解,但x = fin.readline() 不会阅读每一行。 for word in fin 行也从文件中读取行,结果是第一个读取所有偶数行,第二个读取所有奇数行。

标签: python python-3.x subprocess ipython


【解决方案1】:

在提示您输入搜索词之前,您需要阅读整个文件。因此,您需要两个循环——一个用于获取全部数据,另一个用于搜索数据。

这是您更新后的代码的样子。我用一个数组替换了文件输入,以便我可以使用网络工具运行它:

fin=['D1,Tyrannasaurous','D2,Apatasauros','D3,Velociraptor' ]
toys = {}

for word in fin:
    x = word.replace("\n",",").split(",")
    a = x[0]
    b=x[1]
    toys[a]=str(b)

while 1:
    i = input("\nPlease enter the code:")
    if i in toys:
        print(i," is the code for a= ", toys[i],)
    else:
        print('\nTry again')
    if i == 'quit':
        break

在此处输出:https://repl.it/BVxh

【讨论】:

    【解决方案2】:

    将文件读入字典:

    with open('toys.txt') as file:
        toys = dict(line.strip().split(',') for line in file)
    

    以交互方式打印与用户从命令行提供的输入键对应的值,直到收到quit 键:

    for code in iter(lambda: input("Please enter the code:"), 'quit'):
        if code in toys:
            print(code, "is the code for toy:", toys[code])
        else:
            print(code, 'is not found. Try again')
    

    它使用two-argument iter(func, sentinel)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 2022-06-23
      • 2021-12-27
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多