如何在单独的列表中获取结果

2024-10-03 11:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个基于Codefight代码挑战的票价估计器。你知道吗

在你提出要求之前,它能告诉你要花多少钱。它通过这个公式通过近似行驶距离和行驶时间来工作:

(Cost per minute) * (ride time) + (Cost per mile) * (ride distance)


示例

对于

  • 骑乘时间=30
  • 行驶距离=7
  • 每分钟成本=[0.2,0.35,0.4,0.45]
  • 每英里成本=[1.1,1.8,2.3,3.5],输出应为
  • 票价估计器(乘车时间、乘车距离、每分钟成本, 每英里成本=[13.7,23.1,28.1,38]

输出必须在列表中


自:

  • 30*0.2+7*1.1=6+7.7=13.7
  • 30*0.35+7*1.8=10.5+12.6=23.1
  • 30*0.4+7*2.3=12+16.1=28.1
  • 30*0.45+7*3.5=13.5+24.5=38

这是我的密码:

def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):

    for cpm, cpmile in zip(cost_per_minute, cost_per_mile):
        result = round(( ride_time * cpm ) + ( ride_distance * cpmile ), 1)
        print([result])

fareEstimator(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5])

它的输出

[13.7]
[23.1]
[28.1]
[38.0]

我试过使用列表理解来获得TypeError: 'float' object is not iterable

现在请帮我把结果列成这样一个单子。你知道吗

[13.7、23.1、28.1、38]


Tags: 距离列表time时间distance成本costper
3条回答

您只需使用列表理解并从函数返回结果:

def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):    
    return [round(( ride_time * cpm ) + ( ride_distance * cpmile ), 1) 
            for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]

>>> fareEstimator(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5])
[13.7, 23.1, 28.1, 38.0]

不打印,而是附加到一个列表,然后返回:

result = []
for cpm, cpmile in zip(cost_per_minute, cost_per_mile):
    value = round(ride_time * cpm + ride_distance * cpmile, 1)
    result.append(value)
return result

这很容易转换为列表理解;只需将result表达式放在前面:

return [round(ride_time * cpm + ride_distance * cpmile, 1)
        for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]

演示:

>>> def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):
...     return [round(ride_time * cpm + ride_distance * cpmile, 1)
...             for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]
...
>>> fareEstimator(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5])
[13.7, 23.1, 28.1, 38.0]

注意,这个返回新列表,如果您仍然需要打印这个结果,请在调用fareEstimator()的地方打印。你知道吗

问题在于:

print([result])

对于每个结果,您创建一个只包含结果的列表,然后打印它。 您要做的似乎是创建一个空列表,并将每个结果添加到其中。你知道吗

像这样:

def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):
    results = []
    for cpm, cpmile in zip(cost_per_minute, cost_per_mile):
        result = round(( ride_time * cpm ) + ( ride_distance * cpmile ), 1)
        results.append(result)
    print(results)

请参阅https://docs.python.org/3/tutorial/datastructures.html,以了解有关可以对列表执行的操作的更多信息。你知道吗

相关问题 更多 >