内容中心

2026年比较好的宁波节能干燥注塑辅机实力工厂推荐-诺博特(宁波)智能科技有限公司

To solve this problem, we need to read numerical data from a file, compute basic statistical measures (average, maximum, minimum, and count of elements), and write these results to another file.

Approach

  1. Read Data: Open and read the content of the file data.txt. Convert the read content into a list of floating-point numbers.
  2. Compute Statistics:
    • Average: Sum of all numbers divided by the count of numbers.
    • Maximum: The largest number in the list.
    • Minimum: The smallest number in the list.
    • Count: The number of elements in the list.
  3. Write Results: Open the file results.txt and write the computed statistics in a readable format.

Solution Code

# Read data from 'data.txt'
try:
    with open('data.txt', 'r') as data_file:
        content = data_file.read().strip()
        if not content:
            raise ValueError("The file 'data.txt' is empty.")
        numbers = list(map(float, content.split()))
except FileNotFoundError:
    print("Error: 'data.txt' not found.")
    exit(1)
except ValueError as e:
    print(f"Error: {e}")
    exit(1)

# Calculate statistics
average = sum(numbers) / len(numbers)
max_value = max(numbers)
min_value = min(numbers)
count = len(numbers)

# Write results to 'results.txt'
with open('results.txt', 'w') as result_file:
    result_file.write(f"Average: {average:.2f}\n")
    result_file.write(f"Maximum: {max_value}\n")
    result_file.write(f"Minimum: {min_value}\n")
    result_file.write(f"Count: {count}\n")

print("Results have been written to 'results.txt'.")

Explanation

  • Reading Data: The code reads the content of data.txt and splits it into individual strings (using whitespace as the delimiter). These strings are then converted to floating-point numbers to handle both integer and decimal values.
  • Handling Errors: The code checks for common errors like missing files or empty data to ensure robustness.
  • Computing Statistics: Basic Python functions (sum, max, min, len) are used to compute the required statistics.
  • Writing Results: The results are formatted to two decimal places for the average (for readability) and written to results.txt in a clear, line-by-line format.

This approach efficiently processes the data and provides the required output in a structured manner. The code is concise, easy to understand, and handles common edge cases.

诺博特(宁波)智能科技有限公司

诺博特(宁波)智能科技有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?