使用基本python在python中进行多行输入

时间:2017-02-24 05:01:29

标签: python

我正在尝试使用Python解决CodeAbbey中的一些问题。我遇到了试图为这些程序提取输入的问题。我花了很多时间分析如何在不解决问题的情况下获取输入数据。希望有人解释了如何接受输入。

问题:我必须一次性输入以下数字。我尝试过使用'input()',但只需要一行。是否有任何工作以简单的方式做到这一点?我浪费了太多时间来分析各种选项

632765 235464
985085 255238
621913 476248
312397 751031
894568 239825
702556 754421
474681 144592

您可以在此处找到确切的问题:http://www.codeabbey.com/index/task_view/sums-in-loop

2 个答案:

答案 0 :(得分:0)

我的第一次尝试是尝试输入类似" 632765 235464 \ n985085 255238 [...]"所以你可以把它读成一行。如果真正的用户输入,这将是非常hacky并不是一个好主意。

另一个想法:为什么不逐行取输入并将这些行放在列表中/将它们附加到字符串?

编辑:

我在SO上找到了一些代码,但我认为它的python2.7。 ->Here

Python3.X样式将是:

#!/usr/bin/python
input_list = [] 

while True: # Infinite loop, left by userinput
    input_str = input(">") #The beginning of each line.
    if input_str == ".": #Userinput ends with the . as input
        break # Leave the infinite loop
    else:
        input_list.append(input_str) #userinput added to list

for line in input_list: #print the input to stdout
    print(line)

希望这会有所帮助:)

答案 1 :(得分:0)

您可以重复input()直到获得所有数据,例如:

try:
    input = raw_input  # fix for Python 2.x compatibility
except NameError:
    pass

def input_pairs(count):
    pairs = []  # list to populate with user input
    print("Please input {} number pairs separated by space on each new line:".format(count))
    while count > 0:  # repeat until we get the `count` number of pairs
        success = True  # marks if the input was successful or not
        try:
            candidate = input()  # get the input from user
            if candidate:  # if there was some input...
                # split the input by whitespace (default for `split()`) and convert
                # the pairs to integers. If you need floats you can use float(x) instead
                current_pair = [int(x) for x in candidate.split()]
                if len(current_pair) == 2:  # if the input is a valid pair
                    pairs.append(current_pair)  # add the pair to our `pairs` list
                else:
                    success = False  # input wasn't a pair, mark it as unsuccessful
            else:
                success = False  # there wasn't any input, mark it as unsuccessful
        except (EOFError, ValueError, TypeError):  # if any of the conversions above fail
            success = False  # mark the input as unsuccessful
        if success:  # if the input was successful...
            count -= 1  # reduce the count of inputs by one
        else:  # otherwise...
            print("Invalid input, try again.")  # print error
    return pairs  # return our populated list of pairs

然后,只要您需要数字对,就可以调用它:

my_pairs = input_pairs(7)  # gets you a list of pairs (lists) entered by user