出于某种原因,我的代码适用于所有 10 位数字,但不适用于 3-4 位数字。我创建了一个示例概念来尝试简化这一点,以便我可以看到我的逻辑出了什么问题。但是我的示例运行良好,但我的实际代码却没有。我的结论是它必须与从 SQLite 或 CSV 读取数据有关。这是一个很好的示例概念代码:
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.'
这适用于所有长数字,但它不会获得短数字的数据。为什么?