Python 3.x 在python中将列表保存到文件

Python 3.x 在python中将列表保存到文件,python-3.x,numpy,Python 3.x,Numpy,请将列表a、b保存到文件有什么问题 print(type(a[1])) print(type(b)) 给予 错误: TypeError: object of type 'numpy.float64' has no len() 多谢各位 编辑 np.array(a.tolist()) 会失去精度吗 当我使用 with open("file.txt","w") as f: for (x,y) in zip(b,a[1]): f.write("{0},{1}\n".for

请将列表a、b保存到文件有什么问题

print(type(a[1]))
print(type(b))
给予

错误:

TypeError: object of type 'numpy.float64' has no len()
多谢各位

编辑

np.array(a.tolist())
会失去精度吗

当我使用

with open("file.txt","w") as f:
    for (x,y) in zip(b,a[1]):
        f.write("{0},{1}\n".format(b,a[1]))
结果是

[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ],[ 0.990688  0.991408  0.993574 ...,  1.03006   1.0326    1.0325  ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ],[ 0.990688  0.991408  0.993574 ...,  1.03006   1.0326    1.0325  ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ],[ 0.990688  0.991408  0.993574 ...,  1.03006   1.0326    1.0325  ]
列表a和b的打印为:

[ 0.99572325  0.9969785   0.99801075 ...,  1.0412075   1.0423975   1.0432775 ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ]

我想要一个文件中的两列—a列和b列作为所需的输出。

您可以使用pandas库执行以下操作:

import pandas as pd

#create two lists
a = list(range(10))
b = list(range(20, 30))

#create two series from the lists
series_a = pd.Series(a)
series_b = pd.Series(b)

#create a empty dataframe and name the columns
df = pd.DataFrame(columns=['a', 'b'])

#add the series to the dataframe by columns names df['cloumnname']
df['a'] = series_a
df['b'] = series_b

#wtiring the dataframe to an excel file
with pd.ExcelWriter('path/file.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1')

注意:这会将结果保存到excel文件中,它是否必须是您在问题中提到的txt文件?如果是这样,此链接应该会有所帮助:

Numpy数组不是列表。你不能
zip
他们。同样,您的循环是错误的。zip是正常的,但是不要使用
b
a[1]
作为迭代变量。使用类似于
x
y
的东西。谢谢你的建议,我编辑了这个问题。这个文件也可以是csv或xlsx文件吗?如果是这样,您可以从到列表(在熊猫系列中)创建熊猫数据框,并使用dataframe.to_Excel('Path')或dataframe.to_CSV('Path')将其写入Excel或CSV文件。非常感谢您,.xlsx文件很好。
[ 0.99572325  0.9969785   0.99801075 ...,  1.0412075   1.0423975   1.0432775 ]
[ 6430.032  6430.073  6430.112 ...,  6626.907  6626.948  6626.99 ]
import pandas as pd

#create two lists
a = list(range(10))
b = list(range(20, 30))

#create two series from the lists
series_a = pd.Series(a)
series_b = pd.Series(b)

#create a empty dataframe and name the columns
df = pd.DataFrame(columns=['a', 'b'])

#add the series to the dataframe by columns names df['cloumnname']
df['a'] = series_a
df['b'] = series_b

#wtiring the dataframe to an excel file
with pd.ExcelWriter('path/file.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1')