在python中,如何在一个固定的时间间隔内跳过几个ENRTIE?
我有一个包含以下元素的数据文件在python中,如何在一个固定的时间间隔内跳过几个ENRTIE?,python,numpy,Python,Numpy,我有一个包含以下元素的数据文件name.txt: object 1 num 2 24 56 67 object 3 num 4 34 56 78 num 5 count 4 69 78 56 我想删除文本行并生成一个3*3矩阵。有人能帮我写python代码吗。我想运行100个事件的代码 我尝试了以下方法: import numpy as np t = np.genfromtxt('name.txt', usecols=0) m = t[np.isfinite(t)].reshape((3, 3
name.txt
:
object 1
num 2
24
56
67
object 3
num 4
34
56
78
num 5
count 4
69
78
56
我想删除文本行并生成一个3*3矩阵。有人能帮我写python代码吗。我想运行100个事件的代码
我尝试了以下方法:
import numpy as np
t = np.genfromtxt('name.txt', usecols=0)
m = t[np.isfinite(t)].reshape((3, 3))
导入itertools
从itertools导入islice
以open('name.txt')作为fp:
对于itertools.islice中的行(fp,2,无):
打印行
我只能跳过前两行字符串,但我想跳过所有文本行并生成一个3*3矩阵。只保留所需行的一种方法是使用筛选它们。由于要删除/保留的行的模式是规则的,因此我们可以使用 因此,生成矩阵的一种方法是:
from itertools import chain, repeat, compress
lines_filter = chain.from_iterable(repeat([False]*2 + [True]*3, 3))
# will repeat 3 times the sequence 2 x False, 3 x True,
matrix = [[0]*3 for i in range(3)]
with open('test.txt') as f:
lines = compress(f, lines_filter)
values = map(lambda line: int(line.strip()), lines) # or float
# Your question doesn't make clear if the values are given by line
# or column. I assume by line, swap i and j otherwise.
for i in range(3):
for j in range(3):
matrix[i][j] = next(values)
print(matrix)
# [[24, 56, 67], [34, 56, 78], [69, 78, 56]]
我们还可以使用itertools
创建矩阵,但可能更难阅读:
from itertools import chain, repeat, compress
lines_filter = chain.from_iterable(repeat([False]*2 + [True]*3, 3))
# will repeat 3 times the sequence 2 x False, 3 x True
with open('test.txt') as f:
lines = compress(f, lines_filter)
values = map(lambda line: int(line.strip()), lines) # or float
line_items = [iter(values)]*3
matrix = list(map(list, zip(*line_items)))
print(matrix)
# [[24, 56, 67], [34, 56, 78], [69, 78, 56]]
# and if you want it transposed:
t = list(map(list, zip(*matrix)))
print(t)
# [[24, 34, 69], [56, 56, 78], [67, 78, 56]]
或者,使用islice
:
from itertools import chain, repeat, compress, islice
lines_filter = chain.from_iterable(repeat([False]*2 + [True]*3, 3))
# will repeat 3 times the sequence 2 x False, 3 x True
with open('test.txt') as f:
lines = compress(f, lines_filter)
values = map(lambda line: int(line.strip()), lines) # or float
matrix = [list(islice(values, 3)) for i in range(3)]
print(matrix)
# [[24, 56, 67], [34, 56, 78], [69, 78, 56]]
由于您已将问题标记为
numpy
,因此我认为使用numpy
的答案可能有用。您可以尝试以下操作:
import numpy as np
t = np.genfromtxt('name.txt', usecols=0)
m = t[np.isfinite(t)].reshape((3, 3))
然后,对于您的特定示例:
In [44]: import numpy as np
...: t = np.genfromtxt('name.txt', usecols=0)
...: m = t[np.isfinite(t)].reshape((3, 3))
...: print(m)
...:
[[ 24. 56. 67.]
[ 34. 56. 78.]
[ 69. 78. 56.]]
您尝试了什么,遇到了什么问题?我尝试了下面的评论。谢谢。