如何从 python 中的用户输入列表中查找特定号码
How to find a specific number from a user inputed list in python
我想让程序找出特定数字在列表中出现的次数。我在这里做错了什么?
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()
numList
不是数字列表,而是字符串列表。在与 numFind
.
比较之前尝试转换为整数
if int(num) == numFind:
或者,将 numFind
保留为字符串:
numFind = input("Enter a number to look for: ")
...虽然这可能会带来一些并发症,例如如果用户输入 1, 2, 3, 4
作为他们的列表(注意空格)和 2
作为他们的号码,它会说 "Appeared 0 time" 因为 " 2"
和 "2"
不会比较相等。
代码有 2 个问题,首先您将 int
与 str
进行比较,第二个是 count / length
。在 Python 中,当您将 int
除以 int
时,您会得到 int
而不是 float
(正如预期的那样),因此 fraction = flost(count) / length
将适用于你,你还需要将列表中的所有元素转换为整数,可以这样做:
numList = map(int, numInput.split(","))
我想让程序找出特定数字在列表中出现的次数。我在这里做错了什么?
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()
numList
不是数字列表,而是字符串列表。在与 numFind
.
if int(num) == numFind:
或者,将 numFind
保留为字符串:
numFind = input("Enter a number to look for: ")
...虽然这可能会带来一些并发症,例如如果用户输入 1, 2, 3, 4
作为他们的列表(注意空格)和 2
作为他们的号码,它会说 "Appeared 0 time" 因为 " 2"
和 "2"
不会比较相等。
代码有 2 个问题,首先您将 int
与 str
进行比较,第二个是 count / length
。在 Python 中,当您将 int
除以 int
时,您会得到 int
而不是 float
(正如预期的那样),因此 fraction = flost(count) / length
将适用于你,你还需要将列表中的所有元素转换为整数,可以这样做:
numList = map(int, numInput.split(","))