为什么这个代码不能很好地工作?

2024-04-24 04:05:12 发布

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

#This will import time, so that I can break between lines
import time
import random
import os
#This will open the file, and will allow me to print it out
words =open("Words.txt", "r+")
print(words.read())
#This sets the different words to variables
x = 0
y = 0
z = 0
grid = 0

for i in words:
     list_of_words[x] = i.rstrip()
     x = x +1
     grid = [words[i:i + 3] for i in range(0, len(words), 3)]
for x,y,z in grid:
     print(x,y,z)
#This will close the word file
words.close

我有第一部分要做,但当谈到第二部分时,它说我必须有一个int。这是错误消息:

Traceback (most recent call last):
  File "C:\Users\Jamie\Documents\Jamie\Homework\Computing\Coureswork\Computer Science Courseword real.py", line 18, in <module>
    for x,y,z in grid:
TypeError: 'int' object is not iterable

Tags: thetoinimportforclosetimeopen
1条回答
网友
1楼 · 发布于 2024-04-24 04:05:12

得到的错误是因为grid0(您将其初始化为),而不是在第一个循环中为该名称分配列表理解时成为列表。你知道吗

该循环不会做任何事情,因为您已经使用了words文件,其中words.read()位于程序顶部附近。在文件上迭代什么也做不了,因为您已经在末尾了。为了再次读取文件,您需要关闭并重新打开它,或者使用words.seek(0)倒带您在文件中的位置。或者更好的是,如果你不需要的话,不要把整件事读成一个字符串。你知道吗

请注意,即使解决了读取文件的问题,您也会遇到其他问题。例如,您从未定义list_of_words,因此这将导致异常。您还尝试在分配给grid的列表中分割文件。那是不合法的。你知道吗

相关问题 更多 >