Python:For循环在调用时将我的列表减半

2024-04-25 12:12:20 发布

您现在位置:Python中文网/ 问答频道 /正文

一个约127000多字的文件被导入并放入一个列表中

try:
    dictionary = open("dictionary.txt", "r")
except:
    print("Dictionary not found")
    exit()
list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary]

当用户输入一个单词长度时,它会检查以确保单词在参数范围内。你知道吗

def length_check(x):
    while(1):
        x = int(input("Please enter a word length: "))
        if x >= 1 and x <=147:
            return
        else:
            print ('enter proper length')

然后,它取这个单词的长度,对照列表中的单词进行检查,并删除列表中的任何单词,这不等于“单词长度”

def read_and_delete(x):
    i = 0
    for removal in x:
        if len(x[i]) != word_length:
            del x[i]
            i += 1
        elif len(x[i]) == word_length:
            i += 1
        else:
            continue
    print(len(list_of_words))

但由于某种原因,输出的结果正好是列表中单词的一半,我不明白为什么,因为代码中根本没有除法。你知道吗


Tags: ofin列表fordictionarylendef单词
1条回答
网友
1楼 · 发布于 2024-04-25 12:12:20

你犯了一个错误,在遍历列表的同时修改它。你应该避免那样。你知道吗

在您的代码中,del[i]创建一个间隙,然后将数组中所有后续的数字左移一个位置以填充间隙。当你增加i时,你跳过一个元素。你知道吗

为了完整性,这将修复您的代码。你知道吗

def read_and_delete(x):
    i = 0
    for removal in x:
        if len(x[i]) != word_length:
            del x[i]
        elif len(x[i]) == word_length:
            i += 1
        else:
            continue
    print(len(list_of_words))

这里有一个更好的方法

def read_and_delete(x):
    return [word for word in x if len(word) == word_length]

这将返回一个新列表,并且不会更改上一个列表。你知道吗

相关问题 更多 >

    热门问题