简体   繁体   English

特定数字和四舍五入到两位小数的总和

[英]Sum of specific numbers and rounding numbers to two decimal places

I am trying to get the sum of certain numbers from a file without changing the file itself我试图在不更改文件本身的情况下从文件中获取某些数字的总和

1 #person number
Marlon Holmes  #Name
18.86 # First number
13.02 # Second Number
13.36 # Third Number

For the sum of numbers, it needs to be the #First, #second and #third number对于数字的总和,它需要是#First、#second和#third数字

The numbers currently are in cm which have been converted to inches which the two decimal places are necessary for当前数字以厘米为单位,已转换为英寸,因此需要两位小数

My code at present is to provide the top 3 people based on the sum of the #first,#second and #third numbers.我目前的代码是根据#first、#second 和#third 数字的总和提供前3 个人。

Current code:当前代码:

data = []
names = OrderedDict([('Competitor Number', int),
    ('Competitor Name', str),
    ('Cucumber', to_inch),
    ('Carrot', to_inch),
    ('Runner Bean', to_inch)])

with open('veggies_2016.txt') as fobj:
    while True:
        item = {}
        try:
            for name, func in names.items():
                item[name] = func(next(fobj).strip())
            data.append(item)
        except StopIteration:
            break
sorted_data = sorted(data, key=itemgetter('Runner Bean'), reverse = True)
for entry in sorted_data[:3]:
    for key, value in entry.items():
        print value
    print

There are about 50 records in the file that im reading from, which the sum must be added up for all then put in order to find the top 3 and ideally in two decimal places文件中有大约 50 条记录可供我读取,必须将所有记录相加,然后放入前 3 条记录,最好保留两位小数

Code referring to to_inch:参考to_inch的代码:

def to_inch(cm):
    return float(cm) / 2.54

The whole document works around a main menu整个文档围绕一个主菜单工作

To get the sum, I have tried sum(item.entry.items()) but with no success and have also tried "%.2f" for the decimal figures/significant figures but with no success, any help would be appreciated为了得到总和,我试过sum(item.entry.items())但没有成功,也试过"%.2f"小数/有效数字但没有成功,任何帮助将不胜感激

If we disregard reading from the file for now and assume we can put the numbers in a list we can use Python's round() , sum() , and map() .如果我们暂时不考虑读取文件并假设我们可以将数字放入list我们可以使用 Python 的round()sum()map()

Code:代码:

numbers = [18.86, 13.02, 13.36]

def to_inch(cm):
    return cm/2.54

numbers_in_inches = list(map(to_inch, numbers))
print(numbers_in_inches)

numbers_rounded = list(map(round, numbers_in_inches, [0 for _ in numbers]))
print(numbers_rounded)

sum_numbers = sum(numbers_rounded)
print(sum_numbers)

Output:输出:

[7.4251968503937, 5.125984251968504, 5.259842519685039]
[7.0, 5.0, 5.0]
17.0

What is happening:怎么了:

  1. Mapped your function to_inch on each of the items in the list numbers映射你的函数to_inch上每个项目的列表中的numbers
  2. Mapped Python's round() function onto each the values in numbers_in_inches , the reasoning for the list comprehension on the end is it creates a list of 0 's for map() to use for round(number, places) 's places .将 Python 的round()函数映射到numbers_in_inches每个值, numbers_in_inches进行列表理解的原因是它为map()创建了一个0的列表,用于round(number, places)places
  3. Uses Python's sum() to take the sum of all of the numbers, of course, you can just use round(sum_numbers, 0) if you want to round after the sum.使用 Python 的sum()来计算所有数字的总和,当然,如果你想在总和之后round(sum_numbers, 0) ,你可以使用round(sum_numbers, 0) Note: If you want to round after you sum, use math.fsum instead of sum as mentioned by Copperfield in the comments.注意:如果您想求和四舍五入,请使用math.fsum而不是像 Copperfield 在评论中提到的sum

Now to parse the file:现在解析文件:

import re

numbers_names = {}
numbers = []
player_number = ''
name = ''

with open('file.txt', 'r') as f:
    for line in f:
        if '#person number' in line:
            player_number = int(line.split('#')[0])
        elif '#Name' in line:
            name = line.split('#')[0]
        else:
            line_numbers = re.sub(r"[^\d.]", "", line)
            if '.' in line_numbers:
                numbers.append(float(line_numbers))
        if len(numbers) >= 3 and player_number and name:
            numbers_names.update({'player_number': player_number, 'name': name,  'numbers': numbers})
            numbers, player_number, name = [], 0, ''

print(numbers_names)

Output:输出:

{'name': 'Marlon Holmes  ', 'numbers': [18.86, 13.02, 13.36], 'player_number': 1}

How It's parsing the file:它是如何解析文件的:

  1. First opens the file.首先打开文件。
  2. Next iterates over each line in the file. Next 遍历文件中的每一行。
  3. For each line in the file, it sees whether it's a line containing the player's name, the players number, or the numbers that he has.对于文件中的每一行,它会查看该行是否包含玩家姓名、玩家编号或他拥有的号码。

    • Player Number Splits line into the note and the data then takes the data and sets it equal to player_number . Player Number 将行拆分到音符中,然后数据获取数据并将其设置为等于player_number

    • Name Splits line into the note and the data then takes the data and sets it equal to name Name 将行拆分到音符中,然后数据获取数据并将其设置为等于name

    • Numbers He Has It removes all non-word characters except for .他拥有的数字会删除除.之外的所有非单词字符. in the file using re 's re.sub() .在文件中使用rere.sub() Then, checks to see if there is a decimal in the cleaned-up line.然后,检查清理的行中是否有小数。 Finally, if so it appends the line to numbers .最后,如果是这样,它将该行附加到numbers
  4. If all three values are present, it appends them all to the numbers_names dictionary and resets the variables for the next player.如果所有三个值都存在,它会将它们全部附加到numbers_names字典并为下一个玩家重置变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM