gpt4 book ai didi

python - 读取同一行中多个项目的项目

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:43 24 4
gpt4 key购买 nike

我正在尝试让我的程序读取内文件并将其绘制在图表上。当 infile 每行仅包含一个项目时,它起作用,但在这个新文件中,同一行中有多个项目:

Line 1: -4.6653184e-01 -3.9003953e-01 -1.3689525e+00 -2.9784036e-01 -1.2366933e+00 -1.4433164e+00 -1.7245383e+00 -2.2787106e+00 -9.8088629e-01 -1.9053069e+00 -1.7806724e+00 -3.1259933e+00 -2.1796645e+00 -1.8323782e+00 -1.9089487e+00 -3.6322765e+00

Line 2: -8.9710621e-01 -6.2431759e-01 -1.4762999e+00 -2.2668609e-01 -1.6593426e+00 -1.5644687e+00 -2.4312715e+00 -2.8894224e+00 -1.7810424e+00 -2.2357098e+00 -2.8545336e+00 -3.7422563e+00 -3.0884226e+00 -2.9146711e+00 -3.3407812e+00 -5.2601065e+00

我以前能够做到这一点

lines = infile.readlines()

虽然在 for 循环中,但现在我不知道从这里去哪里。我对 python 还很陌生,希望得到帮助。

另外,请注意,大约有 35,000 行,我不能只进入文本文件并在每个条目后“输入”。谢谢!

最佳答案

这取决于你想做什么。从您粘贴的行中,如果您想选择所有值作为单个数据集,您可以将您拥有的内容替换为:

lines = []
[lines.extend(_.split()) for _ in fd.readlines()]
print lines

这将为数组的每个位置提供一个值:

['-4.6653184e-01', '-3.9003953e-01', '-1.3689525e+00', '-2.9784036e-01', '-1.2366933e+00', '-1.4433164e+00', '-1.7245383e+00', '-2.2787106e+00', '-9.8088629e-01', '-1.9053069e+00', '-1.7806724e+00', '-3.1259933e+00', '-2.1796645e+00', '-1.8323782e+00', '-1.9089487e+00', '-3.6322765e+00', '-8.9710621e-01', '-6.2431759e-01', '-1.4762999e+00', '-2.2668609e-01', '-1.6593426e+00', '-1.5644687e+00', '-2.4312715e+00', '-2.8894224e+00', '-1.7810424e+00', '-2.2357098e+00', '-2.8545336e+00', '-3.7422563e+00', '-3.0884226e+00', '-2.9146711e+00', '-3.3407812e+00', '-5.2601065e+00']

如果您想创建一个数据矩阵,其中每列都是一个单独的数据集,那么您可以将 readlines 替换为:

lines = [_.split() for _ in fd.readlines()

这将生成(在您的示例中)一个两行 N 列的矩阵,例如:

[['-4.6653184e-01', '-3.9003953e-01', '-1.3689525e+00', '-2.9784036e-01', '-1.2366933e+00', '-1.4433164e+00', '-1.7245383e+00', '-2.2787106e+00', '-9.8088629e-01', '-1.9053069e+00', '-1.7806724e+00', '-3.1259933e+00', '-2.1796645e+00', '-1.8323782e+00', '-1.9089487e+00', '-3.6322765e+00'],
['-8.9710621e-01', '-6.2431759e-01', '-1.4762999e+00', '-2.2668609e-01', '-1.6593426e+00', '-1.5644687e+00', '-2.4312715e+00', '-2.8894224e+00', '-1.7810424e+00', '-2.2357098e+00', '-2.8545336e+00', '-3.7422563e+00', '-3.0884226e+00', '-2.9146711e+00', '-3.3407812e+00', '-5.2601065e+00']]

关于python - 读取同一行中多个项目的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37863365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com