使用字典而不是if语句

时间:2019-12-13 12:59:44

标签: python dictionary if-statement

我对python非常熟悉,现在我开始学习如何尽可能短而高效地编写代码。

因此,这是我的老师告诉我的一段代码,最好不要在我的代码中重复执行代码块。

他告诉我使用字典而不是if语句,但是由于存在for循环,我不知道该怎么做。

if day == '1':
    for elem in today:
        if city.lower() in elem or city.upper() in elem:
            print(today1[0])
            print(elem)
            cur_execute("INSERT INTO data VALUES(?, ?)", today1[0], elem)
            break

    else:
        print('data was not found')

if day == '2':
    for elem in tomorrow:
        if city.lower() in elem or city.upper() in elem:
            print(tomorrow1[0])
            print(elem)
            cur_execute("INSERT INTO data VALUES(?, ?)", tomorrow1[0], elem)
            break

    else:
        print('data was not found')

if day == '3':
    for elem in aftertomorrow:
        if city.lower() in elem or city.upper() in elem:
            print(aftertomorrow1[0])
            print(elem)
            cur_execute("INSERT INTO data VALUES(?, ?)", aftertomorrow1[0], elem)
            break

    else:
        print('data was not found')

2 个答案:

答案 0 :(得分:3)

您可以尝试:

the_day = { 
    '1': (today, today1),
    '2': (tomorrow, tomorrow1),
    '3': (aftertomorrow, aftertomorrow1)}

selected_day, selected_day1 = the_day[day]
for elem in selected_day:
    if city.lower() in elem or city.upper() in elem:
        print(selected_day1[0])
        print(elem)
        cur_execute("INSERT INTO data VALUES(?, ?)", selected_day1[0], elem)
        break

答案 1 :(得分:2)

您有两个选择,可以将if替换为字典,或者仅替换for循环中不同的值

字典而不是if-条件

if x == 1:
    function1()
if x == 2:
    function2()
if x == 3:
    function3()
# ...

可以转换为:

functions = {1: function1, 2: function2, 3: function3}
functions[x]()

之所以可行是因为函数也是对象,并且可以作为值存储在字典中。

用字典替换值

您还可以通过这种方式更改代码,以便只有一个循环: 例如

days = {'1': today, '2': tomorrow, '3': aftertomorrow}
for elem in days[day]:
    if city.lower() in elem or city.upper() in elem:
        print(days[day][0])
        print(elem)
        cur_execute("INSERT INTO data VALUES(?, ?)", days[day][0], elem)
        break
else:
    print('data was not found')