Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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格式的3x3网格_Python - Fatal编程技术网

列表中Python格式的3x3网格

列表中Python格式的3x3网格,python,Python,我有一个从文本文件生成的列表,需要将其放入3x3网格中。我尝试了多种方法,但它们似乎都适用于较旧版本的Python with open("words.txt") as f: #open/import words from words.txt words = [x.strip() for x in f] #add to list 就是我必须从文本文件中添加单词到列表中的内容。文件中有10个单词,显示9个。我已经有了“从文本文件中删除/添加列表中的一个单词”的功能。不确定是要最后九个还是前九个,如

我有一个从文本文件生成的列表,需要将其放入3x3网格中。我尝试了多种方法,但它们似乎都适用于较旧版本的Python

with open("words.txt") as f: #open/import words from words.txt
words = [x.strip() for x in f] #add to list

就是我必须从文本文件中添加单词到列表中的内容。文件中有10个单词,显示9个。我已经有了“从文本文件中删除/添加列表中的一个单词”的功能。

不确定是要最后九个还是前九个,如果要前九个删除前九个(f),我假设每个单词都在单独的一行:

with open("words.txt") as f: #open/import words from words.txt
    next(f) # skip first?
    words  = [[next(f).strip() for _ in range(3)] for _ in range(3)]
或者使用itertools.islice:

from itertools import islice

with open("words.txt") as f: #open/import words from words.txt
    next(f)
    words = [list(map(str.rstrip,islice(f,None,3))) for _ in range(3)]

只是有点不同,我假设所有单词都包含在一行中。这样我就可以用readline()读取行,拆分并切掉第一个元素。如果我想要前9个,我可以说[:9],或者显然是从包含更多文本的行中选择其他片段

import numpy as np

with open('filename.txt', 'r') as fp:
    words = fp.readline().split()[1:]

threebythree = np.array(words).reshape((3,3))

但我想展示的是,你正在做的实际上是重塑矩阵,这可以通过一个工具包(比如numpy)来完成。首先将列表读入一个数组(一个9维1D数组),然后使用上述命令将其重塑为3,3。本例中的列表“单词”保持不变,以便在需要时进行进一步处理。

这是否会改变列表中的内容。我需要在3x3网格中使用两次列表,还需要比较用输入删除的单词和用用户输入添加的单词?不能在文件对象上重复多次。如果要使用
f.seek(0)
将指针移回文件的开头,并在f上迭代以再次获取每一行。至于改变名单,我不知道你的意思。我提供的代码创建了一个3*3列表