在文本文件中查找数据集的最大值和最小值;有趣的Puzz

2024-05-29 03:04:54 发布

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

在一个数据集中,我需要打印100整数大小的最小数字。 不过,我一直在尝试min(),但这并没有奏效。整个问题是

"Write a Python program which reads in the carbon emissions data from carbon-emissions.txt and performs the following three calculations, each computing an aggregate combining data from all the years in which more than 100 million tonnes of carbon was emitted:

  • Minimum carbon dioxide emissions among these years
  • Maximum carbon dioxide emissions among these years
  • Total sum of the carbon dioxide emissions among these years

Your program should output the values in terms of million tonnes of carbon dioxide, rather than carbon. One tonne of carbon is equivalent to 3.67 tonnes of carbon dioxide, so you can multiply by 3.67 to perform the conversion. You can do the conversion to carbon dioxide either before or after the aggregations"

到目前为止,我所做的是:

for value in open("carbon-emissions.txt"): 
  value_float = float(value)
  if int(value_float) > 100:
    print(value_float)

它将整个数据集转换为float,然后尝试查找大于100的数字,但是这会打印大于100的所有数据。你知道吗

我想在我把一个最大值,一个最小值,以及所有超过100的值加起来之后。一旦我这样做了,我会打印:

print("Minimum Co2 emissions:" + int(min_value)*3.67)
print("Maximum Co2 emissions:" + int(max_value)*3.67)
print("Total Co2 emissions:" + int(sum_value)*3.67)

该计划应为:

Minimum Co2 emissions: 381.68
Maximum Co2 emissions: 36167.85
Total Co2 emissions: 1467460.51

编辑: max的代码如下:

max_sofar = 0
for value in open("carbon-emissions.txt"):
    value_float = float(value)
    max_sofar = max(max_sofar, value_float)

print("Maximum Co2 emissions:", max_sofar*3.67)

然而,我似乎找不到最低限度。我需要使它大于100,但我需要找到这些数字集的最小值。你知道吗


Tags: oftheinvaluefloatmaxintco2
1条回答
网友
1楼 · 发布于 2024-05-29 03:04:54

您应该将所有值都添加到一个列表中,然后对其运行minmaxsum。你知道吗

values = []
with open('carbon-emissions.txt') as f:
   for line in f:
      if line.strip(): # skips empty lines
          value = float(line)
          if value > 100:
               values.append(value * 3.67)

print('The minimum value is: {0:.2f}'.format(min(values)))
print('The maximum value is: {0:.2f}'.format(max(values)))
print('The total is: {0:.2f}'.format(sum(values)))

相关问题 更多 >

    热门问题