【问题标题】:How to cast string back into a list如何将字符串转换回列表
【发布时间】:2013-07-21 02:31:57
【问题描述】:

我有一个清单:

ab = [1, 2, a, b, c]

我做到了:

strab = str(ab).

所以strab 现在是一个字符串。

我想将该字符串转换回列表。

我该怎么做?

【问题讨论】:

  • @aaronman:不,那是错误的。
  • @aaronman:因为这将创建一个包含字符串中每个字符的列表。它不会恢复原始列表。
  • @aaronman 即使它是一个字符列表,你也会得到额外的[s、空格和,s。
  • @aaronman 然后不要用这种讽刺的 cmets 回答 python 问题。

标签: python string list casting


【解决方案1】:

最简单和最安全的方法是使用ast.literal_eval()

import ast

ab = [1, 2, 'a', 'b', 'c']    # a list
strab = str(ab)               # the string representation of a list
strab
=> "[1, 2, 'a', 'b', 'c']"

lst = ast.literal_eval(strab) # convert string representation back to list
lst
=> [1, 2, 'a', 'b', 'c']

ab == lst                     # sanity check: are they equal?
=> True                       # of course they are!

请注意,调用eval() 也可以,但it's not safe 你不应该使用它:

eval(strab)
=> [1, 2, 'a', 'b', 'c']

【讨论】:

    【解决方案2】:

    使用 ast 包:

    import ast
    lst = ast.literal_eval(strab)
    

    【讨论】:

      【解决方案3】:

      在使用序列设置numpy数组元素的上下文中,您可以使用内置连接绕过将其设置为字符串:

      str_list_obj = '-'.join(list_obj)
      

      然后在需要时使用相同的连接器再次拆分字符串序列(前提是它没有出现在列表的字符串中):

      og_list_obj = str_list_obj.split("-")

      【讨论】:

        猜你喜欢
        • 2016-01-12
        • 1970-01-01
        • 1970-01-01
        • 2017-07-10
        • 1970-01-01
        • 1970-01-01
        • 2018-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多