Python 将输入(来自标准输入)转换为列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19202893/
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
Converting input (from stdin) into lists
提问by Noob Coder
I need to convert input(series of integers) into a bunch of lists.
我需要将输入(整数系列)转换为一堆列表。
Sample Input:
样本输入:
3
2
2 2 4 5 7
Sample Output:
示例输出:
list1=[3]
list2=[2]
list3=[2,2,4,5,7]
I am trying to do this:
我正在尝试这样做:
list=[]
import sys
for line in sys.stdin:
list.append(line)
but print list returns
但打印列表返回
['3\n', '2\n', '2 2 4 5 7']
采纳答案by juliomalegria
Use split
to split a string into a list, for example:
使用split
一个字符串分割成一个列表,例如:
>>> '2 2 4 5 7'.split()
['2', '2', '4', '5', '7']
As you see, elements are string. If you want to have elements as integers, use int
and a list comprehension:
如您所见,元素是字符串。如果要将元素作为整数,请使用int
和列表理解:
>>> [int(elem) for elem in '2 2 4 5 7'.split()]
[2, 2, 4, 5, 7]
So, in your case, you would do something like:
因此,在您的情况下,您会执行以下操作:
import sys
list_of_lists = []
for line in sys.stdin:
new_list = [int(elem) for elem in line.split()]
list_of_lists.append(new_list)
You will end up having a list of lists:
您最终将得到一个列表列表:
>>> list_of_lists
[[3], [2], [2, 2, 4, 5, 7]]
If you want to have those lists as variables, simply do:
如果您想将这些列表作为变量,只需执行以下操作:
list1 = list_of_lists[0] # first list of this list of lists
list1 = list_of_lists[1] # second list of this list of lists
list1 = list_of_lists[2] # an so on ...
回答by óscar López
Here's one way:
这是一种方法:
import ast
line = '1 2 3 4 5'
list(ast.literal_eval(','.join(line.split())))
=> [1, 2, 3, 4, 5]
The idea is, that for each line you read you can turn it into a list using literal_eval()
. Another, shorter option would be to use list comprehensions:
这个想法是,对于您阅读的每一行,您都可以使用literal_eval()
. 另一个更短的选择是使用列表推导式:
[int(x) for x in line.split()]
=> [1, 2, 3, 4, 5]
The above assumes that the numbers are integers, replace int()
with float()
in case that the numbers have decimals.
上面假设数字是整数,如果数字有小数,请替换int()
为float()
。