2012-06-14 101 views
0

由於某些原因,我的代碼適用於所有10位數字,但不適用於3-4位數字。我創建了一個示例概念來試圖簡化這一點,以便我可以看到我的邏輯出錯的地方。但我的示例完美,但我的實際代碼不是。我的結論是它必須從SQLite或CSV讀取數據。下面是示例的概念代碼的偉大工程:Python比較缺少短數

test_list = [ (1, 1234567890), (2, 987654321), (3, 123), (4, 4567) ] 
# showing all contents 
print test_list 

# proving it is a list 
print type(test_list) 

# comparison list 
new_list = [ 1234567890, 987654321, 123, 4567, 1567839890, 987654321 ] 

# find k given matching v 
for num in new_list: 
    for k, v in test_list: 
    if v == num: 
     print 'the key of ' + str(num) + ' = ' + str(k) 

這裏在非工作代碼:

def populateTextMsgs(csvfile, db): 
    conn = sqlite3.connect(db) 
    conn.text_factory = str # 8-bit bytestrings 
    cur = conn.cursor() 

    # get subscribers and write to subscriber_list, no problems here 
    cur.execute('SELECT subscriber_id, phone_number FROM subscriber') 
    subscriber_list = cur.fetchall() # this is getting all the subscribers 

    # no problems here 
    # read values from tab-delimited csv file 
    i = 1 # do not use first line (contains headers) 
    reader = csv.reader(open(csvfile, "rU"), delimiter = '\t') 
    for Number, Name, Message, Datetime, Type in reader: 
    # check to ensure name/number not null and not first record 
    if Number and Name and i > 1: 
     # if number starts with '1' then remove first digit 
     if str(Number)[0] == '1': 
     Number = int(str(Number)[1:]) 

     # this is where I think the problem is, but cannot figure out why 
     # return subscriber_id (sid) given phone number 
     for sid, num in subscriber_list: 
     if num == Number: 
      # insert messages into textmsg table 
      cur.execute('INSERT OR IGNORE INTO textmsg (subscriber_id, msg, datetime, type) VALUES (?,?,?,?)', (sid, Message, Datetime, Type)) 
      conn.commit() 

    i += 1 # iterator to ensure first line is not used but others are 

    cur.close() 
    conn.close() 
    print '...Successfully populated textmsg table.' 

這適用於所有的長數字,但它不與短期獲取數據數字。爲什麼?

+0

可能是某種程度上相關的,但不能在你的代碼中找到「是」http://stackoverflow.com/a/133024/315168 –

+1

它肯定應該是'== '因爲它們正在比較值,它們不是同一個對象(一個在來自數據庫表的列表中,另一個來自csv文件)。 – Dan

+0

我測試過了,用'is'代替== == – Dan

回答

1

只需將if num == Number:替換爲if num == int(Number):,你應該很好,你已經轉換了其中的一些,那些以1開頭但不是其他的,csv reader只返回字符串,而sqlite根據列返回不同的類型......因此你是比較字符串和整數...

+0

謝謝!現在,我明白了爲什麼它不起作用,我早先在代碼中解決了它。 – Dan

+0

沒問題,很高興你啓動並運行。 –