Home > database >  Python input array one line
Python input array one line

Time:01-21

I want to be able to input something like [1, 2, 3, 4, 5, 6, 7] and have it return another array like ['a'. 'b', 'c'] How do I do this? I have tried this but I can only do single numbers.

 arr = list(map(int, input("message > ").split()))

CodePudding user response:

You can use string.ascii_lowercase - which is a string of lowercased letters - along with a list comprehension as shown below.

To handle the case of multi-digit numbers, you'll need to separate the numbers in the input, for example using a space character, and then split on this character when processing the user input.

import string

arr = [string.ascii_lowercase[int(i) - 1]
       for i in input("message > ").split(' ')]

print(arr)

Sample interaction with user:

message > 1 3 5 7 9 11
['a', 'c', 'e', 'g', 'i', 'k']

CodePudding user response:

My understanding is that you would like to make multiple lists inside a list from a single input.

If you know how many arrays you want you can use:

arr = [list(map(int, input("message > ").split())) for _ in range(3)]

Output:

message > 1 2 3
message > 1 4 5
message > 1 3 4
[[1, 2, 3], [1, 4, 5], [1, 3, 4]]

if you don't know how many you could use:

arr = [[i] for i in list(input("message > ").split(","))]

Output:

message > 1 2 3, 1 4 5, 1 3 4
[['1 2 3'], [' 1 4 5'], [' 1 3 4']]

In the second just separate the inputs with commas.

  •  Tags:  
  • Related