如何从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
How to make a list from a raw_input in python?
提问by user3481478
So I am taking raw_input
as an input for some list.
所以我把raw_input
一些列表作为输入。
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 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 s
and 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
回答by Perseus14
list = map(int,raw_input().split())
list = map(int,raw_input().split())
We are using a higher order function map
to get a list of integers
.
我们正在使用高阶函数map
来获取integers
.