Multiline user input with list comprehension in Py

2019-05-13 19:47发布

问题:

Total newb to Python here. I'm working on CodeAbbey's problems using Python 3, and I'd like help to make the code for user input shorter.

Let's say I want to get this input from the user:

3
2 3
4 5
6 7

First line is number of cases, and each of the following lines are the cases themselves with 2 parameters. I've figured out to do it in this way so far:

N=int(input('How many cases will you calculate?\n'))
print('Input parameters separated by spaces:')
entr = [list(int(x) for x in input().split()) for i in range(N)]

The thing is I'd rather to ask all the input in the list comprehension, and then assign N=entr[0]. But how do I get the list comprehension to break the input into lines without using range(N)?

I tried:

entr = [list(int(x) for x in input().split()) for x in input()]

but it doesn't work.

回答1:

I don't see the benefit of doing this in a list comprehension, but here is a solution that allows all data to be copy-pasted in:

entr = [list(int(x) for x in input().split())
        for i in range(int(input()))]
N = len(entr)

Your solution was pretty close. The outer iteration just needed to be given something to iterate on (using range()) rather than a single number.