gpt4 book ai didi

Python:如何将具有多个数字的多个列表转换为数组?

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:48 25 4
gpt4 key购买 nike

我有一个文本文件,其中列出了 4 x 3 二进制值:

1 0 1
0 0 1
1 1 0
0 0 1

当我用python读取这个文件时,它是这样的形式:

import numpy as np
with open("test.txt")as g:
p=g.read().splitlines()
q=[];
for m in p:
q.append(int(m));
p=q;

Python 窗口:

>>> p
['1 0 1', '0 0 1', '1 1 0', '0 0 1']

如何将其转化为数组:

array([[ 1.0,  0.0,  1.0],
[ 0.0, 0.0, 1.0],
[ 1.0, 1.0, 0.0],
[ 0.0, 0.0, 1.0]])

最佳答案

到目前为止最简单的解决方案是跳过所有读取您自己的文件并将行转换为列表列表的中间步骤,只使用 numpy.loadtxt() .默认情况下,这些值将是浮点类型,因此您无需执行任何其他操作。

import numpy as np

dat = np.loadtxt('test.txt')

关于Python:如何将具有多个数字的多个列表转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34672044/

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