检查输入是否由逗号分隔的数字列表组成

2024-05-09 01:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想构建一个while循环,如果用户以不正确的方式提供输入,它会说输入无效,然后重试。来自用户的输入应该是用逗号分隔的数字,然后将其存储在列表中。输入如下所示:

number = input("input your number? (separated by comma): ")
number_list = number.split(',')
numbers = [int(x.strip()) for x in number_list]
print(numbers)

但问题是我不知道如何检查输入是否是用逗号分隔的数字。 例如,如果用户输入0,1,它将存储在类似于[0,1]的列表中。当用户输入除“b”以外的任何数字时,它应该要求用户提供正确的输入

所以理想的代码应该是:

# Start a loop that will run until the user a give valid input.
while numbers != 'List of Numbers separated by comma':
   # Ask user for input.
   number = input("input your number? (separated by comma): ")
   number_list = number.split(',')
   numbers = [int(x.strip()) for x in number_list]

   # Add the new name to our list.
   if numbers == 'List of Numbers separated by comma':
       print(numbers)
   else:
       print('Gave an incorrect input, please try again')

谢谢你的帮助


Tags: 用户number列表forinputyourby数字
2条回答

改编自Trenton McKinney标记的副本

请尝试更多测试用例,以防我错了

对于我所尝试的,我得到了结果输出

while True:
    test=input("Nums sep by comma: ")
    test_list = test.split(',')
    try:
        numbers = [int(x.strip()) for x in test_list]
    except:
        print('please try again, with only numbers separated by commas (e.g. "1, 5, 3")')
        continue
    else:
        print(numbers)
        break
print(numbers)

测试

Nums sep by comma: 1, asdf
please try again, with only numbers separated by commas (e.g. "1, 5, 3")
Nums sep by comma: 1, 2, 5
[1, 2, 5]
        

您可以使用正则表达式来查找值,以便只接受某些字符

import re

pattern = re.compile(r"^[0-9\,]*$")
print(pattern.findall("z")
print(pattern.findall("1,2,3,4")

>> []
>> [1,2,3,4]

^[0-9\,]*$的分解

^-字符串的开头

[ ... ] -括号中的字符之一

0-9-介于0和9之间的任何数字

\,-包含逗号,其中\转义特殊的逗号字符

*-零或更多

$-字符串结尾

相关问题 更多 >