How to make a list from a raw_input in python? [duplicate]

怎甘沉沦 提交于 2019-11-27 15:05:53

问题


This question already has an answer here:

  • Get a list of numbers as input from the user 16 answers

So I am taking raw_input as an input for some list.

x= raw_input()

Where I input 1 2 3 4 How will I convert it into a list of integers if I am inputting only numbers?


回答1:


Like this:

string_input = raw_input()
input_list = string_input.split() #splits the input string on spaces
# process string elements in the list and make them integers
input_list = [int(a) for a in input_list] 



回答2:


list = map(int,raw_input().split())

We are using a higher order function map to get a list of integers.




回答3:


You can do the following using eval:

lst = raw_input('Enter your list: ')
lst = eval(lst)
print lst

This runs as:

>>> lst = raw_input('Enter your list: ')
Enter your list: [1, 5, 2, 4]
>>> lst = eval(lst)
>>> print lst
[1, 5, 2, 4]
>>> 



回答4:


Here are some examples and brief explanation for Inputting Lists from users:

You may often need code that reads data from the console into a list. You can enter one data item per line and append it to a list in a loop. For example, the following code reads ten numbers one per line into a list.

lst1 = [] # Create an empty list
print("Enter 10 Numbers: ")
for i in range(10):
   lst1.append(eval(input()))

print(lst1)

Sometimes it is more convenient to enter the data in one line separated by spaces. You can use the string’s split method to extract data from a line of input. For example, the following code reads ten numbers separated by spaces from one line into a list.

# Read numbers as a string from the console
s = input("Enter 10 numbers separated by spaces from one line: ")
items = s.split() # Extract items from the string
lst2 = [eval(x) for x in items] # Convert items to numbers

print(lst2)

Invoking input() reads a string. Using s.split() extracts the items delimited by spaces from string s and returns items in a list. The last line creates a list of numbers by converting the items into numbers.



来源:https://stackoverflow.com/questions/23026324/how-to-make-a-list-from-a-raw-input-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!