Home > OS >  Use Number to get array entry
Use Number to get array entry

Time:03-06

So i want to take any integer as an input and get an output based on arrays like this:

Input: 012346

array = ["a","b","c","d","e","f","g"]

Output: abcdeg

how would i do that?

CodePudding user response:

Use a comprehension. Convert input string to a list of characters then get the right element from array:

inp = '012346'

# For inp to be a string in the case of inp is an integer
out = ''.join([array[int(i)] for i in str(inp)])
print(out)

# Output
abcdeg

Update

How i would treat numbers above 10 since they would get broken down to 1 and 0

Suppose the following input:

inp = '1,10,2,3'
array = list('abcdefghijklmn')

out = ''.join([array[int(i)] for i in inp.split(',')])
print(out)

# Output
'bkcd'

CodePudding user response:

Looks like operator.itemgetter could do the job.

>>> from operator import itemgetter
>>> itemgetter(0, 1, 2, 3, 4, 6)(array)
('a', 'b', 'c', 'd', 'e', 'g')

CodePudding user response:

The input function in Python always returns a string, unless you cast it into another type. So you can loop over the digits of this string, cast the digit ma individually into an integer, and use that to fetch the letters from the list and concatenation them:

str = “”
data = input(“Data? “)
for digit in data:
    str  = array[int(digit)]
  • Related