Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:转换为列表的多行输入_Python_List_Input_Python 3.x_Multiline - Fatal编程技术网

Python:转换为列表的多行输入

Python:转换为列表的多行输入,python,list,input,python-3.x,multiline,Python,List,Input,Python 3.x,Multiline,我有一个编程任务,我需要输入的所有输入都是多行的。 例如: 4 3 10 3 100 5 1000000000 8 或: 我正在尝试将行转换为列表。我不能使用文件,我需要能够使用input语句将它们输入到程序中 我遇到的问题是,我希望输出为: [['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']] [['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']] 所以我

我有一个编程任务,我需要输入的所有输入都是多行的。 例如:

4 3
10 3
100 5
1000000000 8
或:

我正在尝试将行转换为列表。我不能使用文件,我需要能够使用input语句将它们输入到程序中

我遇到的问题是,我希望输出为:

[['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']]
[['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']]
所以我可以用它来完成剩下的程序。但我得到的只是:

[['4', '3']]
我一直尝试使用的代码是:

aString = input(" > ")
aString_list = [x for x in (y.split() for y in aString.split('\n')) if x]
print(aString_list)

我不知道如何让它读其他行。谢谢。

您的代码的问题是,
input()
在您点击回车键后立即停止,要获得连续的输入,您需要使用
while
循环或
for
循环并进行输入,直到用户输入哨兵值:

用于环路和iter

def multiline_input(sentinel=''):
    for inp in iter(input, sentinel):
        yield inp.split()
...         
>>> lis = list(multiline_input())
1 2 3
400 500 600
a b c

>>> lis
[['1', '2', '3'], ['400', '500', '600'], ['a', 'b', 'c']]
使用
循环:

def multiline_input(sentinel=''):
    while True:
        inp = input()
        if inp != sentinel:
            yield inp.split()
        else:
            break
...             
>>> lis = list(multiline_input())
1 2
3 4 5
6 7 8 9
10

>>> lis
[['1', '2'], ['3', '4', '5'], ['6', '7', '8', '9'], ['10']]

这可能是我不明白的,但在这里的代码性能

aString = """
4 3
10 3
100 5
1000000000 8
"""

aString_list = [x for x in (y.split() for y in aString.split('\n')) if x]
print(aString_list)
我们得到一个结果:

[['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']]