Multiline user input with list comprehension in Python 3

你。 提交于 2019-12-07 14:37:40

问题


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.



来源:https://stackoverflow.com/questions/31642577/multiline-user-input-with-list-comprehension-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!