【问题标题】:Make python read 12 from file as 12 not 1 and 2让 python 从文件中读取 12 为 12 而不是 1 和 2
【发布时间】:2017-02-25 02:40:51
【问题描述】:

试图制作一个为不同数量的阶段提供价格的程序。在“tripss.txt”中,第三行是数字 12,python 将其解释为 1 和 2,并给出每个的价格而不是整体的数字,有什么方法可以将其修复为 12?。

infile = open("tripss.txt","r")  
customer_one= infile.readline().strip("\n")     
customer_two= infile.readline().strip("\n")  
customer_three= infile.readline().strip("\n")      
one_to_three_stages="euro 1.55"   
four_to_seven_stages="euro 1.85"   
seven_to_eleven_stages="euro 2.45"  
more_than_eleven_stages="euro 2.85"  
cheapest = ["1","2","3"]       
cheap = ["4","5","6","7"]    
expensive = ["7","8","9","10","11"]     
    for number in customer_three:     
    if number in cheapest:   
        print one_to_three_stages    
    elif number in cheap:     
        print four_to_seven_stages    
    elif number in expensive:    
        print seven_to_eleven_stages   
    else:         
        print more_than_eleven_stages      

【问题讨论】:

  • 你的缩进被破坏了。而且您可能需要将字符串转换为 int (如果这是您想要的),或者不要循环遍历单个字符串(这将使您一个接一个地给您每个字符)。
  • 请提供示例输入。例如,我认为第 3 行只是您的 cmets 的“12\n”,但我不确定。

标签: python file for-loop numbers readlines


【解决方案1】:

在您的代码中,您似乎希望将 customer_three 视为字符串列表。但是,在您的代码中,它是一个字符串,而不是字符串列表,因此 for 循环会迭代字符串的字符(“1”和“2”)。
所以我建议你更换:

customer_three= infile.readline().strip("\n")  

与:

customer_three= infile.readline().strip("\n").split()

【讨论】:

    【解决方案2】:

    你说第三行是数字 12 所以在customer_three= infile.readline().strip("\n") 之后,customer_three 将是字符串"12"。如果随后启动 for 循环 for number in customer_three:number 将被分配字符串的每个元素 - 首先是 "1",然后是 "2"

    解决方案很简单。 customer_three 已经有了你想要的字符串。完全删除for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2010-12-22
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多