python-如何使用列表推导从用户那里获取有效且特定数量的输入,如以下python中给出的语句所示 [英] How to take valid and specific number of inputs from the user using list comprehension as of the statement given below in python

查看:48
本文介绍了python-如何使用列表推导从用户那里获取有效且特定数量的输入,如以下python中给出的语句所示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用上述语句,我想从用户输入的字符串中列出一个列表.

Using the above-mentioned statement I want to take make a list from the string input by the user.

我想限制用户输入的条目数.假设用法给出了一个由5个数字组成的条目,并用空格隔开.拆分后,我得到5个不同的数字,但我想将输入限制为仅4个数字.如何使用上述语句实现此目的?如果不是,那我如何在python的一行中输入不同的数字输入(假设为4)?

I want to limit the number of entries the user makes. Suppose the use gives an entry with 5 numbers separated by blank space. After splitting I get 5 different numbers but I wanted to restrict the input to just 4 numbers. How do I achieve this using the above-mentioned statement? If not then how do I take different numeral inputs (suppose 4) in a single line in python?

推荐答案

您有多种选择.如果您这样做: Ai =([input().split()[:4]]中x的[int(x))即使您输入更多的数字,您也只会取输入的前4个数字数字.但是,如果用户键入的数字少于4个,这将给您带来错误.另外,如果用户键入的不是数字,则int转换将给您一个错误.

You have multiple options to do it. If you do it like this: Ai = ([int(x) for x in input().split()[:4]]) you will only take the first 4 numbers of your input, even if the user types in more numbers. However, this will give you an error if the user types in less than 4 numbers. Also, if the user types in something else than numbers, the int conversion will give you an error.

一种更好的方法是使用正则表达式在列表理解之前验证输入,并仅在符合所需格式的情况下接受输入.此模式与包含1到4个数字(用空格分隔)的字符串匹配,但不匹配超过4个数字或字母的字符串.

A better way to do this would be to validate the input before your list comprehension using regex and only accept it if it's compliant with your desired format. This pattern matches any string that contains between 1 and 4 numbers seperated by spaces, but will not match stings with more than 4 numbers or with letters.

此代码将在无限循环中要求您输入用户输入,并检查用户输入是否与所需格式匹配.如果没有,它将再次要求输入.如果找到匹配项,则循环结束,您列出的理解将被执行.

This code will ask you for user input in an infinite loop and check if the user input matches the format that you want. If not, it asks again for input. If a match is found, the loop ends and you list comprehension gets executed.

import re

pattern = re.compile(r'^(?: ?\d+ ?){1,4}$')

while True:
    user_input = input('Please enter up to four numbers seperated by spaces: ')
    if pattern.search(user_input):
        break
    else:
        print('Invalid input, try again!')

Ai = ([int(x) for x in user_input.split()])

这篇关于python-如何使用列表推导从用户那里获取有效且特定数量的输入,如以下python中给出的语句所示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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