Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python for循环不迭代_Python_Loops_Dictionary - Fatal编程技术网

Python for循环不迭代

Python for循环不迭代,python,loops,dictionary,Python,Loops,Dictionary,我试图循环遍历字符串列表,如果它们的长度等于用户输入的长度,则将它们添加到字典中。当最后一个循环运行时,它只运行一次。我知道这一点是因为字典中的第一个单词有8个字符长,当用户输入为8时,它只打印该单词,而不打印其他8个字符的单词。如果输入为3,则打印空字典。为什么我的循环没有遍历列表中的所有单词 wordLength = raw_input("Enter a word length ") word_dict = {} infile = open("dictionary.txt") for li

我试图循环遍历字符串列表,如果它们的长度等于用户输入的长度,则将它们添加到字典中。当最后一个循环运行时,它只运行一次。我知道这一点是因为字典中的第一个单词有8个字符长,当用户输入为8时,它只打印该单词,而不打印其他8个字符的单词。如果输入为3,则打印空字典。为什么我的循环没有遍历列表中的所有单词

wordLength = raw_input("Enter a word length ")
word_dict = {}
infile = open("dictionary.txt")

for line in infile:
    line = line.strip()
    linelist = line.split(" ")


for word in linelist:
    if len(word) == int(wordLength):
        if len(word) in word_dict:
            word_dict[len(word)] = word_dict[len(word)].append(word)
        else:
            word_dict[len(word)] = word

print word_dict

每次运行第一个循环时,它都会将
linelist
设置为新值,覆盖所有旧值。在第一个循环运行之后,
linelist
将只包含文件最后一行的
split
结果。每次处理文件的一行时,都会丢弃上一行所做的一切

如果要建立字典文件中所有单词的列表,则需要创建一个列表,并在infle循环中的
for行的每次迭代中附加到该列表中


另外,如果每一行只有一个单词,那么在每一行上使用
split
也没有多大意义,因为不需要进行拆分。

第二个循环没有缩进,因此只能在
linelist
的最后一个值上运行它

for line in infile:
    line = line.strip()
    linelist = line.split(" ")
每次执行
linelist=line.split(“”
)时,都会使用最后一行中的单词替换旧的行列表。列表最后只包含最后一行中的单词。如果需要整个文件中的单词,请创建一个行列表并使用新词扩展它:

linelist = []
for line in infile:
    # split with no argument splits on any run of whitespace, trimming
    # leading and trailing whitespace
    linelist += line.split()
#            ^ this means add the elements of line.split() to linelist
因为显然每个单词都有自己的行,所以您甚至不应该使用
split

words = [line.strip() for line in infile]

dictionary.txt文件的格式是什么?我觉得不错。我假设字典中的单词总是用空格分隔,而不是用逗号、句号或其他符号分隔,对吗?每个单词本身都在一行上,那么为什么要拆分这些行?