如何从python中的用户输入列表中查找特定数字

时间:2015-05-11 18:10:58

标签: python list for-loop find

我希望程序能够找到列表中特定数字出现的次数。我在这做错了什么?

def list1():
    numInput = input("Enter numbers separated by commas: ")
    numList = numInput.split(",")
    numFind = int(input("Enter a number to look for: "))
    count = 0
    for num in numList:
        if num == numFind:
            count += 1
    length = len(numList)
    # dividing how many times the input number was entered 
    # by the length of the list to find the %
    fraction = count / length
    print("Apeared",count,"times")
    print("Constitutes",fraction,"% of this data set")
list1()   

2 个答案:

答案 0 :(得分:2)

numList不是数字列表,而是一个字符串列表。尝试转换为整数,然后再与numFind进行比较。

    if int(num) == numFind:

或者,将numFind保留为字符串:

numFind = input("Enter a number to look for: ")

......虽然这可能会引入一些并发症,例如如果用户输入1, 2, 3, 4作为他们的列表(注意空格)并输入2作为他们的号码,它会说"出现0时间"因为" 2""2"不会比较相等。

答案 1 :(得分:1)

代码有两个问题,首先您要将intstr进行比较,第二个是count / length。在使用int划分int时,你会得到一个int,而不是float(正如预期的那样)。所以fraction = flost(count) / length会对你有用,你也是需要将列表中的所有元素转换为整数,可以这样做:

numList = map(int, numInput.split(","))
相关问题