Python 3中具有列表理解功能的多行用户输入 [英] Multiline user input with list comprehension in Python 3

查看:109
本文介绍了Python 3中具有列表理解功能的多行用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是Python的总newb.我正在使用Python 3解决CodeAbbey的问题,我希望帮助缩短用户输入的代码.

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

第一行是案例数,随后的每一行都是案例本身,带有2个参数.到目前为止,我已经想过要这样做:

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)]

我想问的是列表理解中的所有输入,然后分配N = entr [0].但是,如何不使用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)?

我尝试过:

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

但它不起作用.

推荐答案

在列表理解中我看不到这样做的好处,但是这里有一个解决方案,可以将所有数据复制粘贴到其中:

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)

您的解决方案非常接近.只需给外部迭代(使用range())进行迭代即可,而不是使用单个数字.

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

这篇关于Python 3中具有列表理解功能的多行用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆