简体   繁体   English

你如何限制 python 的 input() 函数的输入参数的数量?

[英]How do you limit the number of input arguments for python's input() function?

Let's say I have this:假设我有这个:

maxNumOfArgs = int(input("enter length of list: "))

listOfNums = input("enter space separated list elements: ")

Nothing is stopping the user from entering more arguments than maxNumOfArgs .没有什么能阻止用户输入比maxNumOfArgs更多的参数。 Is there a concise, pythonic way to limit the number of entered arguments in the input() call?是否有一种简洁的 Pythonic 方法来限制input()调用中输入的参数数量?

When you split the str returned by input() , you can limit the number of splits by passing a parameter maxsplit .拆分input()返回的str ,可以通过传递参数maxsplit来限制拆分的数量。

Example:例子:

>>> test = input("enter data: ")
a b c d e f
>>> args = test.split(" ", maxsplit=3)
>>> args
['a', 'b', 'c', 'd e f']

Note that, in the worst case, the array returned by split will have 4 elements, since you limited it to 3 splits.请注意,在最坏的情况下, split 返回的数组将有 4 个元素,因为您将其限制为 3 个拆分。

When you split the second input string, you can then strip off any arguments beyond the requested maximum length当您拆分第二个输入字符串时,您可以剥离超出请求的最大长度的任何参数

# Get requested length
max_num_args = int(input("enter length of list: "))

# Get input string of comma-separated elements
all_inputs = input("enter space separated list elements: ")

# Split string by comma and only keep up to the maximum requested list length
input_values = all_inputs.split(',')[:max_num_args] 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM