Python将字符串分隔成单词和递归

时间:2015-05-18 17:42:19

标签: python string recursion

我试图创建一个接受输入的代码(例如下面的代码)

  

输入:
  BHK158车辆11
  OIUGHH MOTORCYCLE 34.46
  BHK158 VEHICLE 12.000
  TRIR TRUCK 2.0
  BLAS215 MOTORCYCLE 0.001
  结束

并生成一个输出,其中列出了每个车牌号码,总费用列在旁边(例如下面)

  

对应输出:
  OIUGHH:5.8582
  BHK158:5.75
  TRIR:2.666
  BLAS215:0.00017

车牌每公里收费0.25美元(公里数是输入清单中的数字值),卡车每公里收费1.333美元,摩托车每公里收费0.17美元。输出按降序列出。

到目前为止,这是我的代码:

fileinput = input('Input: \n')
split_by_space = fileinput.split(' ')

vehicles = {}


    if split_by_space[1] == 'VEHICLE':
        split_by_space[2] = (float(split_by_space[2]) * 0.25) 
    elif split_by_space[1] == 'TRUCK':
        split_by_space[2] = float(split_by_space[2]) * 1.333 
    elif split_by_space[1] == 'MOTORCYCLE':
        split_by_space[2] = float(split_by_space[2]) * 0.17 

    if split_by_space[0] in vehicles:
        previousAmount = vehicles[split_by_space[0]]
        vehicles[split_by_space[0]] = previousAmount + split_by_space[2]
    else:
        vehicles[split_by_space[0]] = split_by_space[2]

谢谢,非常感谢任何帮助/提示。

1 个答案:

答案 0 :(得分:3)

通过你的代码我注意到了一些事情,python中的列表指示从0开始,而不是1,所以你得到了一堆出界错误。其次,输入只占用输入的第一行,因此它永远不会越过第一行。 .split()默认情况下按\n分割文字,您必须指定是否要按其他内容进行拆分,例如空格。

test.txt内容:

BHK158 VEHICLE 11
OIUGHH MOTORCYCLE 34.46
BHK158 VEHICLE 12.000
TRIR TRUCK 2.0
BLAS215 MOTORCYCLE 0.001

python代码:

fileinput = open('test.txt', 'r')
lines = fileinput.readlines()

vehicles = {}

for line in lines:
    split_by_space = line.split(' ')
    if split_by_space[1] == "VEHICLE":
        split_by_space[2] = (float(split_by_space[2]) * 0.25)
    elif split_by_space[1] == "TRUCK":
        split_by_space[2] = float(split_by_space[2]) * 1.333
    elif split_by_space[1] == "MOTORCYCLE":
        split_by_space[2] = float(split_by_space[2]) * 0.17


    if split_by_space[0] in vehicles:
        previousAmount = vehicles[split_by_space[0]]
        vehicles[split_by_space[0]] = previousAmount + split_by_space[2]
    else:
        vehicles[split_by_space[0]] = split_by_space[2]

输出:

{'BLAS215': 0.00017, 'OIUGHH': 5.858200000000001, 'TRIR': 2.666, 'BHK158': 5.75}