How to get from a list [7,0,8] from [7, 0, 8]? in python
This is my code
l3=input()
l5=l3.translate({Ord("["):None})
l1=l5.translate({Ord("]"):None})
l6=input()
l7=l6.translate({Ord("["):None})
l2=l7.translate({Ord("]"):None})
la1=list(l1.strip().split(","))
la2=list(l2.strip().split(","))
la1=la1[::-1]
la2=la2[::-1]
l11=""
l22=""
for I in la1:
l11 =str(I)
for I in la2:
l22 =str(I)
l555=[]
l111=int(l11)
l222=int(l22)
#print(l111)
#print(l222)
l333=l111 l222
l444=str(l333)
l444=l444[::-1]
for I in l444:
l555.append(int(I))
print(l555)
CodePudding user response:
You could consider using ast.literal_eval
:
>>> from ast import literal_eval
>>> s = input()
[7, 0, 8]
>>> type(s)
<class 'str'>
>>> xs = literal_eval(s)
>>> xs
[7, 0, 8]
>>> type(xs)
<class 'list'>
>>> type(xs[0])
<class 'int'>
CodePudding user response:
To parse the str
as a list
, use str.split(',')
and then cast each number to an int
:
s = input()
l = list(map(int,s[1:-1].split(',')))
print(l)
If that's too hard to read, try this:
s = input()
no_brackets = s[1:-1] #remove first and last character
str_list = no_brackets.split(',')
l = []
for n in str_list:
l.append(int(n))
Also, try to use better variable names; it's quite hard to follow your code.