【问题标题】:Python string to list in list要在列表中列出的 Python 字符串
【发布时间】:2020-01-27 20:37:12
【问题描述】:

我刚刚遇到了一个未解决的解决方案;)

我想将一个字符串放入列表列表中。

string = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'
new_string = string.strip().split('=')
# now new_string[1][:-1] does look like a list of lists but everything i tried i just got a string.

也许这里有人知道我怎么能得到它

data = [[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]]

谢谢

【问题讨论】:

标签: python string list


【解决方案1】:

使用ast库将字符串转换为数据结构:

import ast

# string is a module in python, to avoid aliasing, use
# variable names that ideally don't shadow builtins
mystring = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'

# get everything to the right of the = sign, and you don't need the semicolon
mystring = mystring.strip().split('=')[-1].rstrip(';')

# returns a list
mylist = ast.literal_eval(mystring)

[[0, 0, 110], [1, 0, 0, 0], [1, 0, 0, 0], [9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0]]

【讨论】:

    【解决方案2】:

    eval 也可以正常工作。

    mystring = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'
    
    mystring = mystring.strip().split('=')[-1].rstrip(';')
    
    data = eval(mystring)
    print(data)
    # output: [[0, 0, 110], [1, 0, 0, 0], [1, 0, 0, 0], [9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0]]
    

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 2015-09-30
      相关资源
      最近更新 更多