将2个列表的字符串表示形式转换为列表

时间:2018-12-10 10:41:21

标签: python

我想从字符串中创建列表。 我的琴弦:

[[1544434140,asd,asd,asd]]

如您所见,我的字符串在另一个列表中包含一个列表,如果我想这样做,这是绝对必要的:

[[1544434140,asd,asd,asd][1544434140,asd,asd,asd]]

我已经尝试过:

literal_eval(mystring)

eval(mystring)

但是都从ast.literal_eval抛出这样的异常:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/socketserver.py", line 317, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/local/lib/python3.6/socketserver.py", line 348, in process_request
    self.finish_request(request, client_address)
  File "/usr/local/lib/python3.6/socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/local/lib/python3.6/socketserver.py", line 696, in __init__
    self.handle()
  File "/usr/local/lib/python3.6/http/server.py", line 418, in handle
    self.handle_one_request()
  File "/usr/local/lib/python3.6/http/server.py", line 406, in handle_one_request
    method()
  File "/home/dev/requestHandler.py", line 223, in do_GET
    addrequestResult = rh.addRequestToQue(self.path)
  File "/home/dev/requestHandler.py", line 86, in addRequestToQue
    resultOK = self.addToList(request)
  File "/home/dev/requestHandler.py", line 181, in addToList
    doAdd(request, userque, userhistory)
  File "/home/dev/requestHandler.py", line 143, in doAdd
    userque = literal_eval(userque)
  File "/usr/local/lib/python3.6/ast.py", line 85, in literal_eval
    return _convert(node_or_string)
  File "/usr/local/lib/python3.6/ast.py", line 61, in _convert
    return list(map(_convert, node.elts))
  File "/usr/local/lib/python3.6/ast.py", line 61, in _convert
    return list(map(_convert, node.elts))
  File "/usr/local/lib/python3.6/ast.py", line 84, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x7fa6751838d0>

我知道如何将2个封装列表转换为一个列表吗?

2 个答案:

答案 0 :(得分:0)

根据我的假设,如果asd不是变量,并且在样式列表中需要“,”。如果有的话让我知道

尝试使用此格式字符串eval()将起作用

mystring = "[[1544434140,'asd','asd','asd'],[1544434140,'asd','asd','asd']]"
print eval(mystring)

Result:[[1544434140, 'asd', 'asd', 'asd'], [1544434140, 'asd', 'asd', 'asd']]

答案 1 :(得分:0)

@Narendra Lucky的答案确实有效,但是还有第二种解决方案:

Mylist = json.loads(MyString)