2009-12-07 224 views
1

我是一個python noob,我正在嘗試編寫一個程序,向用戶顯示一個名爲大於X次(用戶X輸入)的電話號碼列表。我已經有程序成功讀取重複項並對它們進行計數(數字存儲在{phoneNumber:numberOfTimesCalled})字典中,但我需要將用戶輸入(一個整數)與字典中的值進行比較,然後打印稱爲X或更多次的電話號碼。這是我的代碼至今:將用戶輸入整數與字典值進行比較? (Python)

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

我認爲這是你在找什麼:

for a in dupNumberCount.keys(): 
    if dupNumberCount[a]>=userInput: 
    print a 
0

另一種解決方案,可以幫助你在學習巨蟒:

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(),它可以像float('12.345')那樣從文字中獲得浮點數。嘗試一下你的自我。

相關問題