Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使python将12从文件中读取为12,而不是1和2_Python_File_For Loop_Numbers_Readlines - Fatal编程技术网

使python将12从文件中读取为12,而不是1和2

使python将12从文件中读取为12,而不是1和2,python,file,for-loop,numbers,readlines,Python,File,For Loop,Numbers,Readlines,尝试制作一个程序,为不同数量的阶段提供价格。在“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.re

尝试制作一个程序,为不同数量的阶段提供价格。在“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      

在你的代码中,你似乎想把CuuleSeri3视为字符串列表。但是,在您的代码中,它是一个字符串,而不是字符串列表,因此for循环对字符串的字符(“1”和“2”)进行迭代。
因此,我建议您更换:

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

customer_three= infile.readline().strip("\n").split()
您说第三行是数字12,因此在
customer\u three=infle.readline().strip(“\n”)
之后,
customer\u three
将是字符串
“12”
。如果随后在customer\u three:中为number启动for循环
,则将为字符串的每个元素分配
number
——首先是
“1”
,然后是
“2”


解决办法很简单
customer\u three
已经有了您想要的字符串。完全删除
循环的

缩进被破坏。您可能需要将字符串转换为int(如果您需要的话),或者不要在单个字符串上循环(这将一个接一个地为您提供每个字符)。请提供示例输入。例如,我认为第3行只是您评论中的“12\n”,但我不确定。