简体   繁体   English

Python Lambda函数-列表索引超出范围

[英]Python Lambda Function — List Index out of Range

I'm new to lambda functions in Python, and I'm trying to work with a CSV file. 我是Python中lambda函数的新手,我正在尝试使用CSV文件。

My file, eggs.csv, will start off as empty. 我的文件eggs.csv将开始为空。 The intent of the CSV file is to store high scores for a small game I'm building for fun. CSV文件的目的是为我正在制作的小游戏存储高分。 Each row in the File will include three values: a username, a high score, and a date/time. 文件中的每一行将包含三个值:用户名,高分和日期/时间。

What this code does (or rather, should do) is read each row of the CSV, and store each row as its own list. 此代码的作用(或应该执行的作用)是读取CSV的每一行,并将每一行存储为自己的列表。 If the CSV has fewer than three rows, it appends a few (for my testing purposes). 如果CSV的行数少于三行,则会附加几行(出于我的测试目的)。 Each of these lists is then appended to current_scores . 这些列表中的每一个都将附加到current_scores

If there are 7 or more rows in current_scores , then it sorts them in descending order based on the 2nd item of the row list (the score). 如果current_scores有7行或更多行,则它将基于行列表的第二项(得分)以降序对它们进行排序。 It checks the last item in the current_scores list, and if the player's high_score (hard-coded for now) is higher than the item, then it removes the last item, and appends the new list (which will be a new row in the CSV) with the player score to current_scores . 它检查current_scores列表中的最后一个项目,并且如果播放器的high_score (目前为硬编码)高于该项目,则它将删除最后一个项目,并追加新的列表(它将是CSV中的新行) )的玩家得分为current_scores

If there are fewer than seven items in current_scores , the player's info is simply appended. 如果current_scores项目少于七个,则仅附加玩家的信息。 The list is then sorted based on the scores of each list inside it(the 2nd item in the list is the score). 然后根据列表中每个列表的得分对列表进行排序(列表中的第二项是得分)。

I am using a lambda function to do the sorting, and I get thrown this error when I run it: 我正在使用lambda函数进行排序,运行时会抛出此错误:

C:\Users\kyle\Desktop\csv_workspace>python text_csv.py
[[], ['Kyle', 40, '03/23/2018'], ['Kyle', 41, '03/23/2018'], ['Kyle', 292, '03/23/2018']]
Traceback (most recent call last):
  File "text_csv.py", line 29, in <module>
    current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True)
  File "text_csv.py", line 29, in <lambda>
    current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True)
IndexError: list index out of range

Why is the list index (presumably of the lamba function) out of range? 为什么列表索引(可能是lamba函数的索引)超出范围? And more importantly, how can I fix it? 更重要的是,我该如何解决?

See my code below: 请参阅下面的代码:

user = "Kyle"
high_score = randint(1, 1000)
day = time.strftime("%m/%d/%Y")
with open('eggs.csv', 'r', newline='') as csvfile:
    scores_reader = csv.reader(csvfile, dialect="excel")
    current_scores = []
    for row in scores_reader:
        current_scores.append(row)
    if len(current_scores) < 3:
        for i in range(0, 3):
            current_scores.append(['Kyle', 40+i, day])
    if len(current_scores) >= 7:
        current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True)

        print(current_scores)
        if high_score > int(current_scores[-1][1]): # if player high score is higher than any of current scores
            current_scores.remove(current_scores[-1]) # remove last item in list
            current_scores.append([user, high_score, day]) # append player high score
            current_scores = sorted(current_scores, key= lambda x: x[1], reverse=True)
    else:
        current_scores.append([user, high_score, day])


    print(current_scores)
    current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True)
with open("eggs.csv", 'w', newline="") as csvfile:
    scores_writer = csv.writer(csvfile, dialect="excel")
    for row in current_scores:
        scores_writer.writerow(row)

It looks like you have an empty row at the beginning: 看起来您开头有一个空行:

[[], ['Kyle', 40, '03/23/2018'], ['Kyle', 41, '03/23/2018'], ['Kyle', 292, '03/23/2018']]

That first entry, [] doesn't have an element at index 1. 第一个条目[]在索引1处没有元素。

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

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