所以我不确定问题是否足够清楚,所以让我举个例子。
如果我有一个两行的数据库,我可以做类似的事情
if something_row_1():
#do_something
if something_row_2():
#do_something
但是我的代码中还有一些函数可以让您向数据库添加行。因此,您不知道在运行程序时需要多少个IF。
是否有任何方法可以在不使用SQL语法而仅使用Python的情况下执行任何操作?
编辑:我正在使用SQLite
答案 0 :(得分:1)
我认为有可能。您可以为此使用循环和列表。
rows = get_list_of_rows_from_db()
do_something = get_do_something_list()
for r in range(0,len(r)):
if rows[r]:
do_something[r]
答案 1 :(得分:0)
我不知道这是否能回答您的问题,但您可以将一套易于维护的规则放在一起,并为记录数量提供一定的灵活性。
如果我很了解您,则必须阅读数据库行,并针对每一行测试不同的条件并执行不同的操作。
在这种情况下,您可以按照以下代码进行操作:
# Suppose you read the database and get the rows
# (Adapt your code to actual rows format)
rows = [
("q1", "w1", "e1", "r1"),
("q2", "w2", "e2", "r2"),
("q3", "w3", "e3", "r3"),
]
# Suppose then that the index of the row says which condition to apply, .e. you know that row1 leads to condition 1 etc...
# Then you can write a "router
# You can define tests for known conditions:
def something_row_1(row):
# FOR EXAMPLE: (return your condition)
return row[1] == "w1"
def something_row_2(row):
# FOR EXAMPLE: (return your condition)
return row[2] == "e2"
# And one for all unknown conditions
def default_test(row):
return True # or whatever
tests = [
something_row_1,
something_row_2,
]
# Define the corresponding actions:
def known_action_1(row):
# FOR EXAMPLE: (perform your own action)
print("Action 1 for row", row)
def known_action_2(row):
# FOR EXAMPLE: (perform your own action)
print("Action 2 for row", row)
def default_action(row):
# FOR EXAMPLE: (perform your own action)
print("Default action")
actions = [
known_action_1,
known_action_2,
]
# You can then route your actions
def route_actions(rows):
for i, row in enumerate(rows):
if i < len(tests):
# Get the test to use
test = tests[i]
# Get the action
action = actions[i]
# Do the corresponding action
else:
test = default_test
action = default_action
if test(row):
action(row)
route_actions(rows)
输出为:
Action 1 for row ('q1', 'w1', 'e1', 'r1')
Action 2 for row ('q2', 'w2', 'e2', 'r2')
Default action
您可以为已知行定义已知操作,为新行/未知行定义默认操作。
希望这能回答您的问题。