Home > database >  Converting a string list including comma values to a list of integers?
Converting a string list including comma values to a list of integers?

Time:10-18

I am very new to programming this was a problem given to me.

Input: c = ['1', '2', ',', '1', '3', ',', '1', '4', ',', '1', '5']

Output: d = [12, 13, 14, 15]

This is what I have tried so far:

d = []
for i in range(len(c)):
            while c[i] != ",":
                c_to_int  = int(c[i])
            d.append(c_to_int)

But this does not seem to be giving me the correct answer. I was wondering what the solution to this problem could be. Thank you! :)

CodePudding user response:

I'm not a huge fan of one liners like this but you could do something like

c = ['1', '2', ',', '1', '3', ',', '1', '4', ',', '1', '5']
d = [int(i) for i in "".join(c).split(",")]

CodePudding user response:

While I can't give you a complete answer, I can give you some tips because this looks like homework.

Try to divide your problem into easier problems.

For example. Start with finding the indices of every comma. Then you could try to find an algorithm, for how to convert a list of string numbers to an int.

# from
['1', '2', '3']
# to
123

Then try to combine these two or add another step. Just don't solve it all at once.

  • Related