You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取碳排放文本文件,计算指定条件下的极值问题求助

解决方法:筛选后计算碳排放数据的极值

Got it, I totally get why you're stuck—using min() directly won't work because it considers all values, not just the ones over 100 million tons. The fix is straightforward: first filter your dataset to only keep entries where emissions exceed 100, then run min() and max() on that filtered list. Let's walk through this with a complete Python program.

Step 1: Assume your data format

First, I'll assume your carbon-emissions.txt looks like this (each line has a year and emission value, separated by a comma):

1990,98.7
1991,102.3
1992,110.5
1993,95.2
1994,120.1

If your delimiter is different (like a tab or space), just adjust the split method in the code below.

Step 2: Complete Python code

def analyze_carbon_emissions(file_path):
    filtered_emissions = []
    filtered_years = []
    
    try:
        with open(file_path, 'r') as file:
            # Uncomment the line below if your file has a header row
            # next(file)
            
            for line in file:
                line = line.strip()
                if not line:
                    continue  # Skip empty lines
                
                # Split line into year and emission value
                year, emission_str = line.split(',')
                try:
                    emission = float(emission_str)
                    # Filter emissions over 100 million tons
                    if emission > 100:
                        filtered_years.append(year)
                        filtered_emissions.append(emission)
                except ValueError:
                    print(f"Skipping invalid line: {line}")
        
        if not filtered_emissions:
            print("No entries found with emissions exceeding 100 million tons.")
            return
        
        # Calculate required metrics
        min_emission = min(filtered_emissions)
        max_emission = max(filtered_emissions)
        avg_emission = sum(filtered_emissions) / len(filtered_emissions)
        
        # Map min/max values back to their respective years
        min_year = filtered_years[filtered_emissions.index(min_emission)]
        max_year = filtered_years[filtered_emissions.index(max_emission)]
        
        # Print results with context
        print("Analysis of emissions over 100 million tons:")
        print(f"- Minimum emission: {min_emission} million tons (Year: {min_year})")
        print(f"- Maximum emission: {max_emission} million tons (Year: {max_year})")
        print(f"- Average emission: {avg_emission:.2f} million tons")
    
    except FileNotFoundError:
        print(f"Error: The file {file_path} was not found.")

# Execute the analysis
analyze_carbon_emissions('carbon-emissions.txt')

Key explanations:

  • Filter first, compute later: We build two lists that only include entries meeting the 100-million-ton threshold. This makes min() and max() work exactly as you need them to.
  • Error handling: Added checks for missing files, invalid data lines, and empty filtered results—so your program won't crash unexpectedly.
  • Year context: We map the min/max emission values back to their years, which adds meaningful context to your results instead of just raw numbers.

Shorter version with list comprehensions

If you prefer more concise code, you can use list comprehensions to filter and process data in one go:

with open('carbon-emissions.txt', 'r') as file:
    # Parse and filter data in one step
    filtered_data = [
        (year, float(emission)) 
        for line in file 
        if line.strip() 
        for year, emission in [line.strip().split(',')] 
        if float(emission) > 100
    ]

if filtered_data:
    # Use key parameter to get the full (year, emission) tuple
    min_entry = min(filtered_data, key=lambda x: x[1])
    max_entry = max(filtered_data, key=lambda x: x[1])
    average = sum(em for _, em in filtered_data) / len(filtered_data)
    
    print(f"Min emission: {min_entry[1]} million tons ({min_entry[0]})")
    print(f"Max emission: {max_entry[1]} million tons ({max_entry[0]})")
    print(f"Average emission: {average:.2f} million tons")
else:
    print("No entries found with emissions over 100 million tons.")

This version uses min() and max() with a key parameter to directly grab the full year-emission pair, which saves you from tracking separate lists for years and values.

内容的提问来源于stack exchange,提问作者D.Ronald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:17:09