我试图实现一个功能来查找列表中的事件,这是我的代码:
def all_numbers():
num_list = []
c.execute("SELECT * FROM myTable")
for row in c:
num_list.append(row[1])
return num_list
def compare_results():
look_up_num = raw_input("Lucky number: ")
occurrences = [i for i, x in enumerate(all_numbers()) if x == look_up_num]
return occurrences
即使我输入上述列表中的数字,我仍然会得到一个空列表而不是发生的事件。
答案 0 :(得分:0)
您的代码执行以下操作:
在#5,脚本失败是因为您正在将元组与字符串进行比较。以下是您正在做的事情的简化示例:
>>> def all_numbers():
... return [(1,5), (2,6)]
...
>>> lucky_number = 5
>>> for i, x in enumerate(all_numbers()):
... print('{} {}'.format(i, x))
... if x == lucky_number:
... print 'Found it!'
...
0 (1, 5)
1 (2, 6)
正如您所看到的,在每个循环中,您的x
是元组,它永远不会等于5
;即使实际存在该行。
您可以让数据库为您完成脏工作,只返回与您的幸运号码匹配的行数:
def get_number_count(lucky_number):
""" Returns the number of times the lucky_number
appears in the database """
c.execute('SELECT COUNT(*) FROM myTable WHERE number_column = %s', (lucky_number,))
result = c.fetchone()
return result[0]
def get_input_number():
""" Get the number to be searched in the database """
lookup_num = raw_input('Lucky number: ')
return get_number_count(lookup_num)
答案 1 :(得分:0)
raw_input返回一个字符串。尝试将其转换为数字。
occurrences = [i for i, x in enumerate(all_numbers()) if x == int(look_up_num)]