简体   繁体   English

生成器和列表理解输入

[英]generator and list comprehension input

My intention is to input 2 lists one after the other after hitting enter on the input, when I run the following line I don't get any input and no error on jupyter.我的目的是在输入上按回车键后一个接一个地输入 2 个列表,当我运行以下行时,我没有得到任何输入,也没有在 jupyter 上出现错误。

N = (list(map(int,input().split())) for _ in range(2))

But when I build a list of lists which is not my intention it works and input is provided.但是当我构建一个列表列表时,它会起作用并提供输入。

N = [list(map(int,input().split())) for _ in range(2)]

I clearly don't understand what is going on here.我显然不明白这里发生了什么。

in your first line you gave a generator expression , this will be executed if you iterate over, you could use在你的第一行你给出了一个生成器表达式,如果你迭代,这将被执行,你可以使用

next(N)

or或者

list(N)

in your second line, you have a list comprehension that will execute your code immediately在你的第二行,你有一个列表理解,可以立即执行你的代码


My intention is to input 2 lists one after the other after hitting enter on the input我的目的是在输入后依次输入 2 个列表

as far as I understand you want to get 2 lists from 1 input, for this you will need to have a separator between lists:据我了解,您想从 1 个输入中获取 2 个列表,为此您需要在列表之间使用分隔符:

sep = '|'
[list(map(int, l.split())) for l in input().split(sep)]
# input: 1 2 3| 0 4 9

output:输出:

[[1, 2, 3], [0, 4, 9]]

also, you can unpack the result in 2 lists after you "grab" and process the input:此外,您可以在“抓取”并处理输入后将结果解压缩到 2 个列表中:

list1, list2  = [list(map(int,input().split())) for _ in range(2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM