python - 将输入(来自标准输入)转换为列表

标签 python arrays list input

我需要将输入(整数系列)转换成一堆列表。

示例输入:

3
2
2 2 4 5 7

示例输出:

list1=[3]
list2=[2]
list3=[2,2,4,5,7]

我正在尝试这样做:

list=[]
import sys
for line in sys.stdin:
    list.append(line)

但是打印列表返回

['3\n', '2\n', '2 2 4 5 7']

最佳答案

使用split将一个字符串拆分成一个列表,例如:

>>> '2 2 4 5 7'.split()
['2', '2', '4', '5', '7']

如您所见,元素是字符串。如果您想将元素作为整数,请使用 int 和列表理解:

>>> [int(elem) for elem in '2 2 4 5 7'.split()]
[2, 2, 4, 5, 7]

所以,在你的情况下,你会做类似的事情:

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)

你最终会得到一个列表列表:

>>> list_of_lists
[[3], [2], [2, 2, 4, 5, 7]]

如果您想将这些列表作为变量,只需执行以下操作:

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 ...

关于python - 将输入(来自标准输入)转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19202893/

相关文章:

python - 如何跨多个服务器轻松切换 Django 1.9.x 中的数据库

python - 生成没有重复列的位向量数组

python - Numpy maskedarray 缺少堆栈函数

python-3.x - 追加列表项会创建重复项

javascript - 如何在 html 页面中处理 jquery?以两个列表为例

python - 将诸如 "6:02PM"之类的仅限时间的字符串转换为日期时间对象?

python - wxPython 语法高亮小部件

java - 这些不同类型的数组减速到底是如何工作的?

PHP 数组 : how to print only array values but not keys

python - 从字符串列表中提取标记集