-1
x =  ['[1867, 1868]', '[6612663]']

Expected Output:

x =  [[1867, 1868], [6612663]]

I tried ,

x = [item.replace("'", "") for item in x]

It didn't work.

Could someone help?

Natasha
  • 1,111
  • 5
  • 28
  • 66
  • 3
    Are you trying to parse stringified lists of integers into actual lists of integers? Please clarify. – ggorlen Aug 06 '19 at 16:31
  • @ggorlen Yes, the input list has been created from the keys of a dictionary. So the keys(lists) are stored as strings. It is not a duplicate of the other question – Natasha Aug 06 '19 at 16:39
  • Thanks for clarifying. Does the duplicate suggestion solve the problem? It seems you can do a list comprehension, so you can combine the two techniques `[ast.literal_eval(e) for e in x]` or `map(ast.literal_eval, x)` for an iterator. I recommend searching the website thoroughly before posting. – ggorlen Aug 06 '19 at 16:40
  • @ggorlen Yes, it solves my problem. Sorry I didn't know about ast.literal and I didn't search with those keywords – Natasha Aug 06 '19 at 16:42
  • 1
    That's OK, it happens. I searched google for "python convert string list to list" to find the answer. – ggorlen Aug 06 '19 at 16:44

1 Answers1

1

You can use ast.literal_eval with a list comprehension:

import ast

x =  ['[1867, 1868]', '[6612663]']
new = [ast.literal_eval(ls) for ls in x]
print(new)

Output:

[[1867, 1868], [6612663]]
ruohola
  • 21,987
  • 6
  • 62
  • 97