python - 使用生成器从文件构造列表
问题描述
我正在编写一个脚本,需要从大文件中的特定位置读取矩阵。文件中感兴趣的位置如下所示:
VOLUME and BASIS-vectors are now :
-----------------------------------------------------------------------------
energy-cutoff : 500.00
volume of cell : 478.32
direct lattice vectors reciprocal lattice vectors
7.831488362 0.000000000 0.000000000 0.127689649 0.000000000 0.000000000
0.000000000 7.773615667 0.000000000 0.000000000 0.128640268 0.000000000
0.000000000 0.000000000 7.856881120 0.000000000 0.000000000 0.127276967
我需要倒数格向量。有很多方法可以获取这些数字,但文件有数千行,所以我不能(不应该)将整个内容存储为行列表。该限制使提取我想要的数据变得更加困难。这是我到目前为止所拥有的:
with open('OUTCAR','r') as read_outcar:
for line in read_outcar:
if 'VOLUME' in line:
for i in range(5): #skip to line with data
next(read_outcar)
buffer = line.split()
x = [float(buffer(i+3)) for i in buffer]
next(read_outcar)
buffer = line.split()
y = [float(buffer(i+3)) for i in buffer]
next(read_outcar)
buffer = line.split()
z = [float(buffer(i+3)) for i in buffer]
break
这里有两个问题:
1.)我不确定我对“下一个”的使用是否正确/合适,但我不知道如何从文件中获取与迭代器关联的当前行之后的行
2.) 我的发电机不工作。解释器引发类型错误,因为我显然试图连接 str 和 int 类型。我想要的是倒数格矩阵中每一行的浮点数列表。
对此的任何帮助将不胜感激。提前致谢。
解决方案
代码有几个问题:
next
返回迭代器的下一项,并且由于您拆分,line
您应该通过以下方式捕获它line = next(read_outcat)
- 然后缓冲区是一个列表,它通过方括号索引,即
buffer[...]
。但是,由于您似乎对最后三个元素感兴趣,您可以通过buffer[-3:]
.
这里修改后的代码:
with open('OUTCAR') as read_outcar:
for line in read_outcar:
if 'VOLUME' in line:
for i in range(5): #skip to line with data
line = next(read_outcar)
buffer = line.split()
x = [float(b) for b in buffer[-3:]]
line = next(read_outcar)
buffer = line.split()
y = [float(b) for b in buffer[-3:]]
line = next(read_outcar)
buffer = line.split()
z = [float(b) for b in buffer[-3:]]
print(f'x = {x}, y = {y}, z = {z}')
break
推荐阅读
- python-3.x - 使用 linalg.norm 计算的 Minkowsky 距离花费不寻常的时间
- node.js - 将 URL 目录存储在 Node/Express 的变量中
- inno-setup - 限制 Inno Setup 中“准备安装”页面上显示的信息
- linux - 几天前显示所有修改文件的Shell脚本
- c# - CollectionView SelectedItem 在 Xamarin 表单中未突出显示
- python - Sum 未在 python 中指定的列表上执行加法
- javascript - React Hook 在 useEffect 中返回基值
- javascript - 需要帮助优化节点列表数组的突变观察者
- javascript - 更改并尝试进行一些调整时,元素数组在类中变得未定义
- r - 如何在 R 中制作队列预期寿命数据表?