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
Get First Date and Last Date of Current Quarter in Python
Append Dataframes Together in for Loop
Pandas Open_Excel() Fails With Xlrd.Biffh.Xlrderror: Can't Find Workbook in Ole2 Compound Document
Cannot Find Reference 'Xxx' in _Init_.Py
Running Multiple Commands Simultaneously from Python
Find Row Where Values for Column Is Maximal in a Pandas Dataframe
Correctly Reading Text from Windows-1252(Cp1252) File in Python
Use Python Extract Images from Excel Sheets
Find Out the Percentage of Missing Values in Each Column in the Given Dataset
How to Get Rid of the B-Prefix in a String in Python
Extract File Name from Read_Csv - Python
Extract Values from Column of Dictionaries Using Pandas
Replace Values of a Numpy Index Array With Values of a List
Count Number of Empty Array Occurrences Within a 2D Array
Pass Variable Between Python Scripts
How to Periodically Execute a Function With Asyncio