[英]How can I print elements from an imported text file in Python?
Okay, so as my school assignment I have been told to import a txt file and store it inside a list, I have done this correctly, and the next step is to print the items in a 3x3 grid. 好的,所以我的作业被告知要导入一个txt文件并将其存储在列表中,我已经正确地做到了,下一步是将项目打印在3x3网格中。 I have come up with a solution however it doesn't seem to be working.. Here is my code:
我想出了一个解决方案,但是它似乎无法正常工作。这是我的代码:
import time
import random
words = open("Words.txt","r")
WordList = []
for lines in words:
WordList.append(lines)
WordList=[line.rstrip('\n')for line in WordList]
print(WordList(0,2))
What my solution was is that I would print out 3 at a time from the list, so I would print position 0, 1 and 2. Then I would print 3, 4 and 5 then I would print 6, 7 and 8 and I would have my solution. 我的解决方案是从列表中一次打印3个,所以我将打印位置0、1和2。然后我将打印3、4和5,然后我将打印6、7和8,然后有我的解决方案。
The answer to my question is simple: 我的问题的答案很简单:
print(WordList[0:3])
print(WordList[3:6])
print(WordList[6:9])
Try splitting the lines into a list and then print the list while adding a new line every third print, don't append the lines to the WordList. 尝试将这些行拆分为一个列表,然后在打印列表的同时每打印第三行添加一个新行,不要将这些行附加到WordList中。
words= words.rstrip('\n')
WordList = words.split(" ")
count = 0
for word in WordList:
if count % 3 == 0:
print("\n")
print (word)
count++
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.