【问题标题】:saving array of string and integers to a text file in python [duplicate]将字符串和整数数组保存到python中的文本文件[重复]
【发布时间】:2017-10-31 10:32:09
【问题描述】:

我有一个 python 列表

temp = [['abc.jpg', 1, 2, 3, 'xyz'], ['def.jpg', 4,5,6, 'xyz']] 

要将它保存为数组,所以我这样做:

temp = np.vstack(temp)

结果:

print(temp)
temp = [['abc.jpg', '1', '2', '3', 'xyz'], ['def.jpg', '4','5','6', 'xyz']]

它将整数转换为字符串。我不希望这种情况发生。

我想将结果保存在文本文件中。

我尝试了以下方法:

np.savetxt("data.txt", temp)

但我收到以下错误:

TypeError: Mismatch between array dtype ('<U8') and format specifier ('%.18e %.18e %.18e %.18e %.18e %.18e')

【问题讨论】:

  • 这样的字符串数组必须以%s 格式保存。要保留对数字显示的更多控制,您需要创建一个结构化数组,可以使用savetxt 保存。 duplicate 排序有助于结构化数组,但不使用 savetxt。我敢肯定会有更新更好的副本。

标签: python string numpy text


【解决方案1】:

试试这个(它保存用“;”分隔的每一行):

 np.savetxt("data.txt", temp, delimiter=" ", newline = "\n", fmt="%s")

【讨论】:

  • 这给出了一个带有abc.jpg 1 2 3 xyz;def.jpg 4 5 6 xyz;的单行文件
  • @Bart 你想怎么保存?
  • np.savetxt("data.txt", temp, delimiter=" ", newline = "\n", fmt="%s") - 这将保存在新行中。非常适合我!谢谢
  • @Blue;哪个 python/numpy/.. 版本?就我而言(Python 3.6、Numpy 1.13),您的解决方案确实有效(无需将 1 转换为 "1"
  • 使用 3.5.3 python 版本和 1.13.3 numpy 版本。我用temp = np.array(temp) 将我的列表变成了一个数组。打印后我得到temp = [['abc.jpg', '1', '2', '3', 'xyz'], ['def.jpg', '4','5','6', 'xyz']] 但是当我打开文本文件时没有字符串。保存为abc.jpg 1 2 3 xyz def.jpg 4 5 6 xyz
猜你喜欢
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
相关资源
最近更新 更多