【问题标题】:Convert list of string representations of lists of strings of floats separated by spaces to list of lists of integers将由空格分隔的浮点字符串列表的字符串表示形式列表转换为整数列表列表
【发布时间】:2017-09-06 20:07:11
【问题描述】:

我有一个如下所示的列表:

['['0.' '1.' '0.']', 
 '['1.' '0.' '0.']', ....,
 '['0.' '1.' '1.']']

我希望它在 Python 中看起来像这样:

[[0, 1, 0], 
 [1, 0, 0],
 [0, 1, 1]]

我无法使用 strip()、split() 和 ast.literal_eval() 来解决这个问题。谢谢!

【问题讨论】:

  • 您的原始列表是非法的。请检查引号和逗号。

标签: python string list type-conversion


【解决方案1】:

你可以试试这个:

import re
s = ["['0.' '1.' '0.']", "['1.' '0.' '0.']", "['0.' '1.' '1.']"]
new_data = [map(int, list(eval(re.sub("\.", '', i))[0])) for i in s]

输出:

[[0, 1, 0], [1, 0, 0], [0, 1, 1]]

没有评估的解决方案:

s = ["['0.' '1.' '0.']", "['1.' '0.' '0.']", "['0.' '1.' '1.']"]
new_data = [map(int, re.findall("\d+", i[1:-1])) for i in s]

输出:

[[0, 1, 0], [1, 0, 0], [0, 1, 1]]

【讨论】:

猜你喜欢
  • 2023-03-25
  • 2021-10-29
  • 2017-11-24
  • 2019-04-16
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多