如何在Python中使用.split为变量分配未知数量的数字输入?

时间:2019-03-26 14:18:42

标签: python python-3.x

我的任务是创建一个程序,该程序对1-100之间的数字进行计数。

我现在遇到的问题是使用.split将每个输入分配给一个变量,但是只要大于10,用户就可以输入他们想要的数字。我很确定我需要使用某种列表,但我的知识有限,需要一些指导!

numberList = input("Enter 1 to 100 ")

Check = numberList.replace(" ","")

4 个答案:

答案 0 :(得分:0)

您可以这样做:

numberList = input("Enter at least 10 integers between 1 and 100: ").split(" ")

if len(numberList) < 10:
    print("Enter at least 10 integers between 1 and 100: ")

计算每个数字出现的次数:

from collections import Counter

count = Counter(numberList) # eg count = [1,4,9,7,1]
for k,v in count.items():
    print(str(k) + " appears " + str(v) + " times")

答案 1 :(得分:0)

编写一个循环,该循环连续解析输入并将识别的数字添加到列表中,直到该列表至少包含10个数字。

numbers = []
while True:
    n = 10 - len(numbers)
    if n <= 0:
        break
    s = input("Enter at least {} more numbers: ".format(n))
    for v in s.split(" "):
        try:
            v = int(v)
        except ValueError:
            continue
        numbers.append(v)

答案 2 :(得分:0)

因此,您想创建一个整数列表,如果用户输入错误,则输出错误。遵循“求饶远比得到许可容易”的原则。也就是说,只需尝试将数字转换为整数,如果某些操作失败,则中止任务。例如:

while True:
    userInput = input("Enter at least 10 integers between 1 and 100: ")
    try:
        numberList = [int(substring) for substring in userInput.split(" ")]
        if len(numberList) < 10:
            print("Enter at least 10 numbers")
        else:
            break
    except ValueError:
        print("You entered a non-numeric character; please try again")

最后,您要计算每个数字的出现次数。最好的方法(我认为)是Counter集合。只需执行以下操作

from collections import Counter
counter = Counter(numberList)

答案 3 :(得分:0)

要拆分输入,根据您的问题,我认为这看起来像'1 2 45 12',只需使用.split(' '),就像其他人已经指出的那样。这将为您提供值列表,但以字符串格式。要将它们转换为整数,可以使用map,它将对列表的每个元素应用一个操作并返回一个迭代器,该迭代器可以转换为新列表:

numberList = list(map(int, numberList))

如果该列表的元素之一无法转换为整数,则会引发ValueError异常。用try... except捕获该错误以打印错误消息。

对于第二部分,我将简单地遍历列表中的所有项目,使用list.count(item)info),它将返回该项目的出现次数,并存储具有已经检查过,请放在单独的列表中,以避免再次检查任何内容。

代码:

numberList = input("Enter at least 10 integers between 1 and 100: ").split(' ')
if len(numberList) < 10:
    numberList.extend(input("Enter at least {} more integers between 1 and 100: ".format(10-len(numberList))).split(' '))

try:
    numberList = list(map(int, numberList))
except ValueError:
    print("You entered a non-numeric character; please try again!")

print("You have entered {} integers.".format(len(numberList)))

checked_list = []

for i in numberList:
    if i not in checked_list:
        print("The integer {} occured {} time(s).".format(i, numberList.count(i)))
        checked_list.append(i)

输出:

Enter at least 10 integers between 1 and 100: 1 2 3 4 5 6 7
Enter at least 3 more integers between 1 and 100: 8 1 2
You have entered 10 integers.
The integer 1 occured 2 time(s).
The integer 2 occured 2 time(s).
The integer 3 occured 1 time(s).
The integer 4 occured 1 time(s).
The integer 5 occured 1 time(s).
The integer 6 occured 1 time(s).
The integer 7 occured 1 time(s).
The integer 8 occured 1 time(s).