terça-feira, 26 de janeiro de 2021

Python - Obtenha uma lista como entrada do usuário

Frequentemente encontramos uma situação em que precisamos pegar um número / string como entrada do usuário. Neste artigo, veremos como obter como entrada uma lista do usuário.

Exemplos:

Entrada: n = 4, ele = 1 2 3 4
Saída:   [1, 2, 3, 4]

Entrada: n = 6, ele = 3 4 1 7 9 6
Saída: [3, 4, 1, 7, 9, 6]

Código # 1: exemplo básico

# creating an empty list
lst = []

# number of elemetns as input
n = int(input("Enter number of elements : "))

# iterating till the range
for i in range(0, n):
    ele = int(input())

    lst.append(ele) # adding the element

print(lst)

Resultado:

 
Código # 2: com manipulação de exceção

# try block to handle the exception
try:
    my_list = []

    while True:
        my_list.append(int(input()))

# if the input is not-integer, just print the list
except:
    print(my_list)

Resultado:

 
Código # 3: Usando map()

# number of elements
n = int(input("Enter number of elements : "))

# Below line read inputs from user using map() function
a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n]

print("\nList is - ", a)

Resultado:

 
Código # 4: Lista de listas como entrada

lst = []
n = int(input("Enter number of elements : "))

for i in range(0, n):
    ele = [input(), int(input())]
    lst.append(ele)

print(lst)

Resultado:

Código # 5: usando compreensão de lista e definição de tipos

# For list of integers
lst1 = []

# For list of strings/chars
lst2 = []

lst1 = [int(item) for item in input("Enter the list items : ").split()]

lst2 = [item for item in input("Enter the list items : ").split()]

print(lst1)
print(lst2)

Resultado:

Artigo escrito por dileep1998 e traduzido por Acervo Lima de Python | Get a list as input from user.

0 comentários:

Postar um comentário