python - 查找前 10 个并将其从厘米转换为英寸 - Python

标签 python python-2.7

我正在从文件中读取数据,如下所示,它是一个 .dat 文件:

1
Carmella Henderson
24.52
13.5
21.76
2
Christal Piper
14.98
11.01
21.75
3
Erma Park
12.11
13.51
18.18
4
Dorita Griffin
20.05
10.39
21.35

文件本身包含 50 条记录。从这些数据中,我需要人员编号、姓名和第一个编号,如下所示:

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

我已经有了读取数据的代码,但是我无法根据 #First 数字获取前 10 个结果

前 10 名中的#First 数字目前以厘米为单位,但需要转换为英寸,我不确定如何在读取数据的同时将前 10 名和转换结合起来

读取数据的代码:

 with open('veggies_2016.txt', 'r') as f:
        count = 0
        excess_count = 0
        for line in f:
            if count < 3:
                print(line)
                count += 1
            elif count == 3 and excess_count < 1:
                excess_count += 1
            else:
                count = 0
                excess_count = 0

如上所述,代码读取文件,就像 #Person number、#name 和 #first number 一样,但是 #first number 需要转换为英寸,然后需要对所有数据进行排序以找到前 10 个

还必须对#第二个数字和#第三个数字重复此过程,但是它们的代码与#第一个数字是分开的

我尝试读取数据,然后附加到列表中,对其进行排序并从中转换,但没有成功,任何帮助将不胜感激

完整代码:

from collections import OrderedDict
from operator import itemgetter
import pprint
def menu():
    exit = False


    while not exit:
        print("To enter new competitior data, type new")
        print("To view the competition score boards, type Scoreboard")
        print("To view the Best Overall Growers Scoreboard, type Podium")
        print("To review this years and previous data, type Data review")
        print("Type quit to exit the program")

        choice = raw_input("Which option would you like?")

        if choice == 'new':
            new_competitor()
        elif choice == 'Scoreboard':
            scoreboard_menu()
        elif choice == 'Podium':
            podium_place()
        elif choice == 'Data review':
            data_review()
        elif choice == 'quit':
            print("Goodbye")
            raise SystemExit

"""Entering new competitor data: record competitor's name and vegtables lengths"""

def competitor_data():
    global competitor_num
    l = []

    print("How many competitors would you like to enter?")

    competitors = raw_input("Number of competitors:")

    num_competitors = int(competitors)

    for i in range(num_competitors):

        name = raw_input("Enter competitor name:")
        Cucumber = raw_input("Enter length of Cucumber:")
        Carrot = raw_input("Enter length of Carrot:")
        Runner_Beans = raw_input("Enter length of Runner Beans:")

        l.append(competitor_num)
        l.append(name)
        l.append(Cucumber)
        l.append(Carrot)
        l.append(Runner_Beans)

        competitor_num += 1

    return (l)
def new_competitor():
    with open('veggies_2016.txt', 'a') as f:
        for item in competitor_data():
            f.write("%s\n" %(item))
def scoreboard_menu():
    exit = False

    print("Which vegetable would you like the scoreboard for?")

    vegetable = raw_input("Please type either Cucumber, Carrot or Runner Beans:")

    if vegetable == "Cucumber":
        Cucumber_Scoreboard()
    elif vegetable == "Carrot":
        Carrot_Scoreboard()
    elif vegetable == "Runner Beans":
        Runner_Beans_Scoreboard()

def Cucumber_Scoreboard():
    exit = True

    print("Which year would you like the Scoreboard from?")

    scoreboard = raw_input("Please type a year:")

    if scoreboard == "2015":
        cucumber_veg_2015()
    elif scoreboard == "2014":
        cucumber_veg_2014()
    elif scoreboard == "2016":
        cucumber_veg_2016()


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

names = OrderedDict([('Competitor Number', int),
                     ('Competitor Name', str),
                     ('Cucumber', cucumber_veg_2016),
                     ('Carrot', float),
                     ('Runner Bean', float)])
data = []
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

pprint.pprint(sorted(data, key=itemgetter('Cucumber'))[:10])

最佳答案

解决方案

将数据读入字典列表是可行的:

from collections import OrderedDict
from operator import itemgetter
import pprint

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

names = OrderedDict([('person_number', int),
                     ('name', str),
                     ('first', to_inch),
                     ('second', float),
                     ('third', float)])
data = []
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

pprint.pprint(sorted(data, key=itemgetter('first'))[:10])

输出:

[{'first': 4.76771653543307,
  'name': 'Erma Park',
  'person_number': 3,
  'second': 13.51,
  'third': 18.18},
 {'first': 5.897637795275591,
  'name': 'Christal Piper',
  'person_number': 2,
  'second': 11.01,
  'third': 21.75},
 {'first': 7.893700787401575,
  'name': 'Dorita Griffin',
  'person_number': 4,
  'second': 10.39,
  'third': 21.35},
 {'first': 9.653543307086613,
  'name': 'Carmella Henderson',
  'person_number': 1,
  'second': 13.5,
  'third': 21.76}]

逐步

此辅助函数将厘米转换为英寸:

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

我们使用有序字典来保存我们想要按顺序读取的不同项目的名称。该值是我们用来转换每个项目的读取值的函数:

names = OrderedDict([('person_number', int),
                     ('name', str),
                     ('first', to_inch),
                     ('second', float),
                     ('third', float)])

我们从一个空列表开始:

data = []

并打开我们的文件:

with open('veggies_2016.txt') as fobj:

我们做一些没有明确结束的事情,并且每次都会创建一个新的字典item:

    while True:
        item = {}

我们尝试从文件中读取直到它完成,即直到我们得到一个 StopIteration 异常:

        try:
            for name, func in names.items():
                item[name] = func(next(fobj).strip())
            data.append(item)
        except StopIteration:
            break

我们遍历订单字典names的键和值并调用每个 值,即我们使用 next() 检索的下一行的函数 func()。 这会将条目转换为所需的数据类型,并为 first 进行厘米-英寸转换。读取一个人的所有项目后,我们将字典附加到列表 data 中。

最后,我们按键 first 排序并打印出第 10 个条目 (我的示例文件少于 10 个条目):

pprint.pprint(sorted(data, key=itemgetter('first'))[:10])

与您的代码集成:

您需要将代码放入函数podium_place()中:

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

def podium_place():
    names = OrderedDict([('Competitor Number', int),
                         ('Competitor Name', str),
                         ('Cucumber', cucumber_veg_2016),
                         ('Carrot', float),
                         ('Runner Bean', float)])
    data = []
    with open('veggies_2016.txt') as fobj:
        while True:
            item = OrderedDict()
            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('Cucumber'), reverse=True)
    for entry in sorted_data[:10]:
        for key, value in entry.items():
            print key, value
        print

menu()

最后您需要调用menu()。另外,如果 top 表示最大的在前,则需要反向排序(见上文)。

关于python - 查找前 10 个并将其从厘米转换为英寸 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36235070/

相关文章:

django - AbstractUser Django 完整示例

Python 多处理通过 argparse 和 pyinstaller 抛出错误

python - sys 模块位于哪里,或者如何在 Win 11 和 Python 中找到它

python - 将陀螺仪数据用于十字准线 GUI

python - 从终端解耦的过程仍然输出 Traceback 到终端

python - 操作系统错误 : [Errno None not found] 2 - error when launching jupyter on Windows

string - Python连接一个字符串和一个变量

python-2.7 - urllib IOError : [Errno socket error] [Errno 54] Connection reset by peer

python-2.7 - Visual Studio Code : No tests discovered, 请检查测试的配置设置

python - 拆分 pybind11 模块和自动类型转换问题