2012-06-14 60 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

没问题,很高兴你启动并运行。 –