gpt4 book ai didi

python - 从 .txt 文件 Python 3.4.1 中查找中位数和众数

转载 作者:行者123 更新时间:2023-11-28 18:42:15 24 4
gpt4 key购买 nike

我正在尝试从“numbers.txt”文件中的数字列表中确定中位数和众数。我对 python 非常陌生,并且有零编码经验。

到目前为止,这是我计算平均值、总和、计数、最大值和最小值的方法,但我不知道从这里到哪里去。

number_file_name = 'numbers.txt'
number_sum = 0
number_count = 0
number_average = 0
number_maximum = 0
number_minimum = 0
number_range = 0

do_calculation = True
while(do_calculation):

while (True):
try:
# Get the name of a file
number_file_name = input('Enter a filename. Be sure to include .txt after the file name: ')
random_number_count = 0

print('')

random_number_file = open(number_file_name, "r")
print ('File Name: ', number_file_name, ':', sep='')

print('')

numbers = random_number_file.readlines()
random_number_file.close
except:
print('An error occured trying to read', random_number_file)
else:
break

try:
number_file = open(number_file_name, "r")

is_first_number = True

for number in number_file:
number = int(number) # convert the read string to an int

if (is_first_number):
number_maximum = number
number_minimum = number
is_first_number = False

number_sum += number
number_count += 1
if (number > number_maximum):
number_maximum = number
if (number < number_minimum):
number_minimum = number

number_average = number_sum / number_count
number_range = number_maximum - number_minimum

index = 0
listnumbers = 0
while index < len(numbers):
numbers[index] = int(numbers[index])
index += 1


number_file.close()
except Exception as err:
print ('An error occurred reading', number_file_name)
print ('The error is', err)
else:
print ('Sum: ', number_sum)
print ('Count:', number_count)
print ('Average:', number_average)
print ('Maximum:', number_maximum)
print ('Minimum:', number_minimum)
print ('Range:', number_range)
print ('Median:', median)

another_calculation = input("Do you want to enter in another file name? (y/n): ")
if(another_calculation !="y"):
do_calculation = False

最佳答案

如果你想找到medianmode在这些数字中,您需要跟踪到目前为止遇到的实际数字。您可以创建 list持有所有数字,或 dictionary将数字映射到您看到这些数字的频率。现在,让我们根据这些数字创建一个(排序的)列表:

with open("numbers.txt") as f:
numbers = []
for line in f:
numbers.append(int(line))
numbers.sort()

或更短:numbers = sorted(map(int, f))

现在,您可以使用各种 builtin functions计算计数、总和、最小值和最大值

count = len(numbers)
max_num = max(numbers)
min_num = min(numbers)
sum_of_nums = sum(numbers)

使用数字列表也可以非常快速地计算众数和中位数:

median = numbers[len(numbers)//2]
mode = max(numbers, key=lambda n: numbers.count(n))

关于python - 从 .txt 文件 Python 3.4.1 中查找中位数和众数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24812172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com