简体   繁体   English

如何在 python 中只为 input().split() 设置 n 个输入?

[英]How to set only n number of inputs for input().split() in python?

Problem : 1.The first line contains an integer n, denoting the number of elements in the tuple.问题: 1.第一行包含一个整数n,表示元组中元素的数量。 2.The second line contains n space-separated integers describing the elements in tuple. 2.第二行包含 n 个以空格分隔的整数,描述元组中的元素。

Sample Input(correct):样本输入(正确):

2 
3 6 

sample input(wrong):样本输入(错误):

2
3 6 8  

Example:例子:

n=int(input())  #denotes number of elements should be in a tuple 
integer_list = tuple(map(int, input().split()))  # how to modify this line to take only n space separated inputs

#suppose if n=2 in first line then 
#In second line I need only 2 space-separated inputs(since n=2) i.e 3 9(or any two),
 but not more than or less than n numbers. 
  **For Example**:5 7 3(which is >n) or 5(which is <n))

The following code works, but I do not think it's possible to create the tuple in one line:以下代码有效,但我认为不可能在一行中创建元组:

def main():
    n = 0
    while True:
        try:
            n = int(input())
        except ValueError:
            print("Wrong type entered (must enter integer number). Enter again: ")
            continue
        else:
            break
    if n == 0:
        return -1
    integer_list = []
    string_input = input()
    count = 0
    for i in string_input.split():
        if count == n:
            break
        x = 0
        try:
            x = int(i)
        except ValueError:
            return -1
        else:
            integer_list.append(x)
            count += 1
    if count != n:
        return -1
    integer_tuple = tuple(integer_list)
    print(f"The tuple: {integer_tuple}")
    return 0


if __name__ == "__main__":
    main()

It will ask the user again and again for an integer if they have not entered one (as the first input), and then only creates a tuple if n subsequent space-separated integer numbers are entered (not less than n or more than n, and not if there is an invalid input).如果用户没有输入一个整数(作为第一个输入),它将一次又一次地询问用户一个整数,然后仅在输入 n 个后续空格分隔的整数(不小于 n 或大于 n,如果输入无效,则不会)。

Hope this helps.希望这可以帮助。

Instead of input() , define your own function that checks for the condition, and raise exception if condition failed.代替input() ,定义您自己的检查条件的函数,如果条件失败则引发异常。

Example:例子:

def get_input(n):
    string_splits=input().split(' ')
    if len(string_splits)!=n:
        raise Exception("Invalid input")
    return string_splits

n=int(input()) 
integer_list = tuple(map(int, get_input(n))

If you want the output only takes n input and ignore the rest of it wheter it less or more than n value, you could try this:如果您希望输出只接受 n 个输入并忽略它的其余部分,无论它小于还是大于 n 值,您可以试试这个:

n=int(input())
integer_list = tuple(map(int, input().split()))
if len(integer_list) != n: integer_list = tuple(integer_list[0:n]) # add this
print(integer_list)

or using function and exception handling:或使用函数和异常处理:

def input_tuple(i, n):
    i = i.split()
    i = [int(num) for num in i if num.isnumeric()] # ignores non-digit
    return tuple(i[0:n])

while True:
    try:
        n = int(input())
    except ValueError:
        print("Numbers only!")
        continue
    else:
        break

integer_list = print(input_tuple(input(), n))

Example #1:示例 #1:

 2 3 9 (3, 9)

Example #2:示例 #2:

 2 5 7 3 (5, 7)

Example #3:示例#3:

 1 5 7 3 (5,)

Example #4:示例 #4:

 4 5 7 3 (5, 7, 3)

暂无
暂无

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

相关问题 python 中的 N 个 set() 输入 - N number of set() inputs in python 如何使无效输入仅出现在数字输入中? 以及如何将输入转换为列表并增加每个输入的计数? - How do I make the invalid input appear for only number inputs? And how do I turn the inputs into a list and increase the count for every input? 如何在python中接受n个列表的输入? - How can take input of n number of lists in python? 如何根据python中n个测试用例读取输入? - How to read input according to n number of test cases in python? 在 python 3 中,如何在数组中获取 N(从用户读取)数量的输入? - How can i take N(read from user) number of inputs in an array, in python 3? Python 如何仅在选定的分隔符后的值是数字时拆分字符串? - Python How to split string only if value post selected delimiter is a number? 如何拆分字符串并仅获取 python 中的第一个字符串(数字)? - how to split string and take only the first string (a number) in python? 从python中的单行取n个整数输入 - Taking n number of integer inputs from a single line in python 如何在Python中设置常规选项以在各处仅显示N位数字? - How to set a general option in Python to display only N digits everywhere? 在python中验证测验,以便重新进行测验的唯一有效输入是“ y”或“ n”? - Validating a quiz in python such that the only valid inputs for retaking the quiz are 'y' or 'n'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM