简体   繁体   English

如何在Python中从导入的文本文件中打印元素?

[英]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.

相关问题 在Python中:如何将文本文件中的元素打印为字符串,就像出现在文件中一样? - In Python: How do I print the elements as a string from a text file the same way as it appears in the file? 如何在 python 中打印文本文件的特定部分? - How can I print specific parts of a text file in python? 如何打印文本文件的某些部分? Python - How can I print certain parts of a text file? Python 如何将打印 output 写入 Python 中的文本文件? - How can I write the print output to a text file in Python? Python 如何将带有字符串和整数的列表打印到文本文件中 - Python How can I print a list with strings and intergers to a text file 如何在python中使用熊猫访问导入的csv文件中的元素? - How to access elements from imported csv file with pandas in python? 我应该如何使用 python 从 txt 文件中打印格式化文本? - How should I print formated text from a txt file with python? 如何从我的代码根据包含特定字符串选择的文本文件的行打印元素? - How can I print elements from lines of a text file that my code selects based on its inclusion of a particular string? 如何根据从文本文件导入的数据创建 Python 字典? - How to create a Python dictionary from data imported from a text file? 如何从 Python 中的 .txt 文件打印单个列表? - How can I print a single list from a .txt file in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM