我是一个python noob,我正在尝试编写一个程序,向用户显示一个名为大于X次的电话号码列表(用户输入X)。我有程序成功读取重复项并计算它们(数字存储在{phoneNumber:numberOfTimesCalled}的字典中,但我需要将用户输入,一个整数与字典中的值进行比较,然后打印被叫X次或更多次的电话号码。到目前为止,这是我的代码:
import fileinput
dupNumberCount = {}
phoneNumLog = list()
for line in fileinput.input(['PhoneLog.csv']):
phoneNumLog.append(line.split(',')[1])
userInput3 = input("Numbers called greater than X times: ")
for i in phoneNumLog:
if i not in dupNumberCount:
dupNumberCount[i] = 0
dupNumberCount[i] += 1
print(dupNumberCount.values())
userInput = input("So you can view program in command line when program is finished")
基本上,我无法弄清楚如何将字典值转换为整数,将用户输入整数与该值进行比较,并打印出与字典值对应的电话号码。任何帮助都非常感谢!
顺便说一下,我的字典有大约10,000个键:值组织如下:
'6627793661': 1, '6724734762': 1, '1908262401': 1, '7510957407': 1
希望我已经为您提供了足够的信息来帮助我完成该计划!
答案 0 :(得分:0)
我认为这就是你要找的东西:
for a in dupNumberCount.keys():
if dupNumberCount[a]>=userInput:
print a
答案 1 :(得分:0)
另一种解决方案,可以帮助你学习python:
import fileinput
dupNumberCount = {}
# Create dictionary while reading file
for line in fileinput.input(['PhoneLog.csv']):
phoneNum = line.split(',')[1]
try:
dupNumberCount[phoneNum] += 1
except KeyError:
dupNumberCount[phoneNum] = 1
userInput3 = input("Numbers called greater than X times: ")
# iteritems method give you a tuple (key,value) for every item in dictionary
for phoneNum, count in dupNumberCount.iteritems():
if count >= userInput3:
print "Phone %s has been called %d" % (phoneNum, count)
还有一件事,你不需要将计数值转换为整数,因为它已经是一个整数。无论如何,如果你需要转换一个文字整数(例如'2345'),那么就有内置函数int('2345')。还有float(),它可以像浮点数('12 .345')一样从文字中获取浮点数。试试你自己。