I'm trying to solve a problem that I'm facing. I wanted to convert a list of integers to a single integer(join all the elements of the list) and then split them to their original form. for example for the code below(assume I have a function that deals with the index of the y and the list) so if put in 'chart' for y
y = list(input("enter name"))
List=[1,2,3,4,5]
for i,p in enumerate(List):
y[i] = p
print('list is'y)
s = int(''.join([str(int) for int in List]))
print('joined form of the list is', s)
def dec():
t = [', '.join([str(int) for int in List])]
print('original form is', t)
dec()
I want the out put to be
List is [1, 2, 3, 4, 5]
joined form of the list is 12345
original form is [1, 2, 3, 4, 5]
instead for the original form I get a single string. How do I solve this?
CodePudding user response:
int is a function in python (it translates the string you give it in an integer). I would advise against using that word to designate a variable, however short lived.
Now, the join method of the string class is a function that returns a string made up of all the elements of an iterator (here, your integer list), seperated by the string. So, what you are doing with that code line :
t = [', '.join([str(int) for int in List])]
is making a list made of one element, the string made up by all the elements in the List, separated by commas.
If you want to convert all the integers to strings and make a list out of that, you should just skip the "join" part :
t = [str(i) for i in yourList]
And if you want to get back an integer list from a string you can do what Corallien or Bruno suggested.
CodePudding user response:
Your code returns a list of 1 element which is a string representation of your list:
>>> [', '.join([str(i) for i in l])]
['1, 2, 3, 4, 5']
Use instead:
l = [1, 2, 3, 4, 5]
# encode from list
n = int(''.join([str(i) for i in l]))
# decode from number
o = [int(i) for i in str(n)]
Output:
>>> l
[1, 2, 3, 4, 5]
>>> n
12345
>>> o
[1, 2, 3, 4, 5]
CodePudding user response:
you can make them all togethrer by making a for loop and multiply previous result with 10 and adding existing digit
# your code goes here
array = [1,2,3,4,5]
result = 0
for digit in array:
result = result*10 digit
print(result)
output
12345
CodePudding user response:
You almost got it right. all you need to do is change t = [', '.join([str(int) for int in List])]
to t = [int(i) for i in List]
y = list(input("enter name"))
List=[1,2,3,4,5]
for i,p in enumerate(List):
y[i] = p
print('list is',y)
s = int(''.join([str(int) for int in List]))
print('joined form of the list is', s)
def dec():
t = [int(i) for i in List]
print('original form is', t)
dec()