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

时间:2017-05-19 03:42:11

标签: python list dictionary for-loop

一个约有的文件。导入127,000多个单词并将其放入列表

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')

然后它接受单词长度并根据列表中的单词进行检查并删除列表中的任何单词,这不等于&#34; word_length&#34;

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))

但由于某种原因,输出结果恰好是列表中单词的一半,我无法理解为什么代码中根本没有任何区别。

1 个答案:

答案 0 :(得分:0)

你错误地在列表中进行迭代并在同一时间修改它。你应该总是避免这种情况。

在你的代码中,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]

这会返回一个新列表,但不会更改前一个列表。