-3

I have looked at other posts in regard to this. However, they all seem to use list comprehension, thus not allowing for checks on each individual element of the 2d array.

I am wanting to print a 2d array, containing some strings and some ints. Since I am converting those ints into an octal representation using {:o}, I want to be able to check whether an element of the array is an int or string before printing it. Since printing a string with {:o} throws an error.

# Desired outcome:
[['s', 9], [0, 1]]

's' 11
 0   1

Help would be much appreciated as I cannot figure out how to do this.

Wizard
  • 1,533
  • 4
  • 19
  • 32

1 Answers1

2

This map the right format to the value in the list according to his type (str or int).

values = [['s', 9], [0, 1]]

for pair in values:
    print(*map(lambda value: ('{:o}' if isinstance(value, int) else '{}').format(value), pair))

output:

s 11
0 1

You can add tick if you want with "'{}'" instead of '{}'.

TwistedSim
  • 1,960
  • 9
  • 23