Python - Converting a List of 2 Digit String Numbers to a List of 2 Digit Integers

python - converting a list of 2 digit string numbers to a list of 2 digit integers

The core of your solution will be taking the string and converting it to an integer:

def str_to_int(number):
return sum((ord(c) - 48) * (10 ** i) for i, c in enumerate(number[::-1]))

This method takes your number in, enumerates over it from the end and then converts the ASCII value of each character to its numeric representation and then makes sure it will occupy the proper digit in the overall number.

From there, you can use map to convert the entire list:

intsList = list(map(str_to_int, numsList))

Sublist, converting multi digit string to list of single integers

A simple way is to flatten the list using a nested list comprehension, then convert each character in the string to integer.

Here's how you can modify your code:

mylist = [[], ['0000000'], ['2200220'], ['2222220'], ['2200220'], ['2000020'], []]
print([[int(z) for z in y] for x in mylist for y in x])
#[[0, 0, 0, 0, 0, 0, 0],
# [2, 2, 0, 0, 2, 2, 0],
# [2, 2, 2, 2, 2, 2, 0],
# [2, 2, 0, 0, 2, 2, 0],
# [2, 0, 0, 0, 0, 2, 0]]

in python how do I convert a single digit number into a double digits string?

In python 3.6, the fstring or "formatted string literal" mechanism was introduced.

f"{a:02}"

is the equivalent of the .format format below, but a little bit more terse.


python 3 before 3.6 prefers a somewhat more verbose formatting system:

"{0:0=2d}".format(a)

You can take shortcuts here, the above is probably the most verbose variant. The full documentation is available here: http://docs.python.org/3/library/string.html#string-formatting


print "%02d"%a is the python 2 variant

The relevant doc link for python2 is: http://docs.python.org/2/library/string.html#format-specification-mini-language



Related Topics



Leave a reply



Submit