Home > Back-end >  How to convert to 1-dimensional list a list of a string that is list that contains int elements
How to convert to 1-dimensional list a list of a string that is list that contains int elements

Time:02-08

Can't figure out how to make a proper 1-dimensional list out of

a = ['[2,5911,3391,10687,9796,15870,11533]']
a[1:-1]

i want to get [2,5911,3391,10687,9796,15870,11533]

Slices don't seem to work there

Is there any elegant way to do it without writing 2 for loops Appreciate all the help

CodePudding user response:

You have to first get the string a[0] then remove the brakets: a[0][1:-1] then you can use .split() like so:

a = ['[2,5911,3391,10687,9796,15870,11533]']
a = a[0][1:-1].split(',')
print(a)

Output:

['2', '5911', '3391', '10687', '9796', '15870', '11533']

You can also get the integers (if that's what you're after) using a list comprehension like so:

a = ['[2,5911,3391,10687,9796,15870,11533]']
a = [int(item) for item in a[0][1:-1].split(',')]
print(a)

Output:

[2, 5911, 3391, 10687, 9796, 15870, 11533]

CodePudding user response:

import ast
a = ['[2,5911,3391,10687,9796,15870,11533]']
ast.literal_eval(a[0])

Output:

[2, 5911, 3391, 10687, 9796, 15870, 11533]

CodePudding user response:

You can use the standard package json for that, in particular the loads method that can deserialize a string:

import json

a = ['[2,5911,3391,10687,9796,15870,11533]']

json.loads(a[0])
# [2, 5911, 3391, 10687, 9796, 15870, 11533]

Or if you expect a to contain more than just one element:

a_converted = [json.loads(_el) for _el in a]
# [[2, 5911, 3391, 10687, 9796, 15870, 11533]]

The advantage here is that this will work even if the string contains other data types like floats or strings.

  •  Tags:  
  • Related