如何在Python中枚举文本文档中的列表并对其进行排序

时间:2018-11-21 13:53:48

标签: python python-3.x python-2.7 sorting enumerate

我正在尝试使用文本文档枚举python中的列表。我已经阅读了文档,但似乎无法对其进行排序或枚举。目的是在比赛结束时召唤他们,对他们进行排序,然后按完成顺序对其进行枚举。

输出始终为: (['18:44'],生成器对象枚举为0x0000000003143630) 我不确定为什么要说“发电机对象在0x0000000003143630枚举”或如何枚举排序后的列表。

def get_sec(time_str):
    h, m = time_str.split(':')
    return int(h) * 3600 + int(m) * 60
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
with open("Race_Results_Sample.txt", "r")as myList:
    myList = myList.read()
    myList = [l.split(",") for l in myList.splitlines()]
    myList = sorted(myList, key=lambda kv: kv[1])
for line in myList:
    num, last, org, time = line
    place = []
    place.append(time)
    placenum = enumerate(sorted(place))
    print(place, placenum)
for line in myList:
    num, last, org, time = line
    new_time = get_sec(time)
    mile = round((((new_time/ 3.10686)/60)/60), 3)
    mile = str(mile)
    print ('{:<20s}{:<5s}{:<5s}{:<7s}{:<10s}'.format(last, num, org, time, mile))

第一个“ for mylist中的行”只是一项测试,以了解其如何单独工作。我最终将其放置在第二个“ for mylist中的行”部分中,以进一步清理代码。在此先感谢您的帮助。

这是当前的输出

(['18:44'], generator object enumerate at 0x0000000003143630>)
(['18:23'], generator object enumerate at 0x0000000003143678>)
(['18:28'], generator object enumerate at 0x0000000003143630>)
(['18:36'], generator object enumerate at 0x0000000003143678>)
(['19:05'], generator object enumerate at 0x0000000003143630>)
(['19:10'], generator object enumerate at 0x0000000003143678>)
(['18:22'], generator object enumerate at 0x0000000003143630>)
(['18:03'], generator object enumerate at 0x0000000003143678>)
(['18:49'], generator object enumerate at 0x0000000003143630>)
(['19:01'], generator object enumerate at 0x0000000003143678>)
(['18:33'], generator object enumerate at 0x0000000003143630>)
(['18:45'], generator object enumerate at 0x0000000003143678>)
(['18:55'], generator object enumerate at 0x0000000003143630>)
(['18:58'], generator object enumerate at 0x0000000003143678>)
(['18:09'], generator object enumerate at 0x0000000003143630>)

以退出代码0结束的过程

1 个答案:

答案 0 :(得分:2)

enumerate不返回列表,而是一种特殊的生成器。写

placenum = list(enumerate(sorted(place)))

,则程序的行为将更有意义。或者,您可以直接在enumerate()循环中使用(消费)对for的调用,就好像它是一个列表一样。例如

for rank, value in enumerate(sorted(place)):
    print(rank, value)