I am going currently through the book Supercharged Python and there is one problem, that I would like to try to optimize. I want to create a string for.format for a variable size of a 2D array.
def print_2dArray_opt(lst: list):
width = 1
row_string = ''
for r in lst:
for c in r:
temp = len(str(c))
row_string = row_string + '{:{w}}' + ' '
if temp > width:
width = temp
row_string = row_string + '\n'
print(row_string.format(lst, w = width)) # That of course doesn't work
print_2dArray_opt([[1, 10, 100, 200],
[1, 10, 100, 200],
[1, 10, 100, 200],
[1, 10, 10000, 200]
])
But I can't figure out how to formulate that print statement so that it can work. Any suggestions?
try this format style
f'{c:{width}}'
so fixed_code:
def print_2dArray_opt(lst: list):
width = 1
row_string = ''
for r in lst:
for c in r:
temp = len(str(c))
if temp > width:
width = temp
row_string = row_string + (f'{c:{width}}').strip() + ' '
row_string = row_string + "\n"
print(row_string.strip())
print_2dArray_opt([[1, 10, 100, 200],
[1, 10, 100, 200],
[1, 10, 100, 200],
[1, 10, 10000, 200]
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.