如何从python中的raw_input制作列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23026324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:08:40  来源:igfitidea点击:

How to make a list from a raw_input in python?

pythonlistpython-2.7raw-input

提问by user3481478

So I am taking raw_inputas an input for some list.

所以我把raw_input一些列表作为输入。

x= raw_input()

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

我在哪里输入1 2 3 4如果我只输入数字,我将如何将其转换为整数列表?

采纳答案by shaktimaan

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] 

回答by Jocelyn

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.

有时以空格分隔的一行输入数据更方便。您可以使用字符串的 split 方法从输入行中提取数据。例如,以下代码将从一行中以空格分隔的十个数字读取到一个列表中。

# 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 sand returns items in a list. The last line creates a list of numbers by converting the items into numbers.

调用input()读取一个字符串。使用s.split()从字符串中提取由空格分隔的项目s并返回列表中的项目。最后一行通过将项目转换为数字来创建数字列表。

回答by A.J. Uppal

You can do the following using eval:

您可以使用以下方法执行以下操作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]
>>> 

回答by Perseus14

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

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

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

我们正在使用高阶函数map来获取integers.