如何在没有很多if / elif / elif / ...条件的情况下在代码中查找数据?

时间:2019-05-09 16:14:13

标签: python python-3.x

这是我的一个个人项目,现在我的程序是基于我根据每个季节的剧集编号(不同的季节有不同的情节数量)和标题制作的词典,编写大量的if语句。我得到了预期的结果,但是我仍然试图寻找一种更高级的方法,例如使用函数,列表推导或对象以更优雅地用更少的代码行显示它。

我一直在尝试通过谷歌搜索和教程来弄清楚如何使用其他方法之一,但是我无法解决如何将其应用于我的特定程序来获得结果而没有所有这些个人的想法if语句。

epTitles1 = {"1" : "The Gang Gets Racist",
             "2" : "Charlie Wants an Abortion",
             "3" : "Underage Drinking: A National Concern",
             "4" : "Charlie Has Cancer",
             "5" : "Gun Fever",
             "6" : "The Gang Finds a Dead Guy",
             "7" : "Charlie Got Molested"}

epTitles2 = {"1" :  "Charlie Gets Crippled",
             "2" : "The Gang Goes Jihad",
             "3" :  "Dennis and Dee Go on Welfare",
             "4" : "Mac Bangs Dennis' Mom"  ,
             "5" : "Hundred Dollar Baby"    ,
             "6" : "The Gang Gives Back",
             "7" : "The Gang Exploits a Miracle",
             "8" : "The Gang Runs for Office",
             "9" : "Charlie Goes America All Over Everybody's Ass",
             "10" : "Dennis and Dee Get a New Dad"}


x = int(input("Enter a season between 1 and 13 or 0 for random season: "))

print("You selected season:", x)

if x == 0:
    randomSeason = random.randint(1,13)
    print("Random season:", randomSeason)

    if randomSeason == 1:
        episode = random.randint(1,7)           
        print("Episode:", episode)

        if episode == 1:
            print(epTitles1["1"])
        elif episode == 2:
            print(epTitles1["2"])
        elif episode == 3:
            print(epTitles1["3"])
        elif episode == 4:
            print(epTitles1["4"])
        elif episode == 5:
            print(epTitles1["5"])
        elif episode == 6:
            print(epTitles1["6"])
        elif episode == 7:
            print(epTitles1["7"])

    if randomSeason == 2:
        episode = random.randint(1,10)           
        print("Episode:", episode)

        if episode == 1:
            print(epTitles2["1"])
        elif episode == 2:
            print(epTitles2["2"])
        elif episode == 3:
            print(epTitles2["3"])
        elif episode == 4:
            print(epTitles2["4"])

# same pattern continues for each season (13 seasons) 

我只想学习和理解哪种方法/方法将有助于以更实际的方式压缩我的代码以及如何做到。

3 个答案:

答案 0 :(得分:2)

将数据存储在字典中。外层字典引用季节,内层字典具有部件号和该部分的标题:

import random

# see below for a user input safe variant
def get_random_title_of_radnom_season(data):
    season = random.choice(list(data))   # replace with int numeric user input
    nr = random.choice(list(data))       # replace with int numeric user input
    title = data.get(season, {0:"does not exists"}.get(nr,0)    

    return f"Season {season} title {nr} was {title}"


# first index is the season, its value is a dict with partnr, title  
d = {1 : { a: f"Title {a}" for a in range(1,15) },
     2 : { a: f"Title {a}" for a in range(1,10) }, 
     3 : { a: f"Title {a}" for a in range(1,4)  } }

print(get_random_title_of_radnom_season(d))

这是扩大dict理解后数据的外观:

{1: {1: 'Title 1',         2: 'Title 2',         3: 'Title 3',
     4: 'Title 4',         5: 'Title 5',         6: 'Title 6',
     7: 'Title 7',         8: 'Title 8',         9: 'Title 9',
     10: 'Title 10',      11: 'Title 11',       12: 'Title 12',
     13: 'Title 13',      14: 'Title 14'},
 2: {1: 'Title 1',         2: 'Title 2',         3: 'Title 3',
     4: 'Title 4',         5: 'Title 5',         6: 'Title 6',
     7: 'Title 7',         8: 'Title 8',         9: 'Title 9'},
 3: {1: 'Title 1',         2: 'Title 2',         3: 'Title 3'}}

多个输出:

Season 3 title 3 was Title 3    
Season 3 title 1 was Title 1    
Season 3 title 2 was Title 2    
Season 2 title 4 was Title 4    
Season 1 title 9 was Title 9

如果您不喜欢“裸”字典,也可以考虑使用named tuples


要使其成为用户输入的证明,而不是使用字典中的随机数:

def get_user_title_of_radnom_season(data, season, nr): 
    title = data.get(season, {}).get(nr,False)
    return f"Season {season} title {nr} was {title}" if title else "Does not exist"

print(get_user_title_of_radnom_season(d, 99, 99))

会为任何不合适的键打印"Does not exist"

答案 1 :(得分:0)

您可以通过这种方式制作字典

epTitles1 = {1:"s1ep1", 2:"s1ep2", 3:"s1ep3"}
epTitles1 = {1:"s2ep1", 2:"s2ep2", 3:"s2ep3"}

或者您甚至可以为所有季节使用一个列表字典(或列表列表)

epTitles = { 1:["s1ep1", "s1ep2", "s1ep3"], 2:["s2ep1", "s2ep2", "s2ep3"] }

然后您可以通过这种方式访问​​它们

print("You selected season:", x)
if x == 0:
    randomSeason = random.randint(1,13)
    print("Random season:", randomSeason)

    episode = random.randint(1,7)           
    print("Episode:", epTitles[randomSeason][episode-1])

您也可以将随机选择的剧集范围保存在元组的字典中,以最大程度地减少代码,因此最终代码将像这样

epTitles = { 1:["s1ep1", "s1ep2", "s1ep3"], 2:["s2ep1", "s2ep2", "s2ep3"] }
epRanges = { 1:(1,7), 2:(1,10) }

x = int(input("Enter a season between 1 and 13 or 0 for random season: "))
print("You selected season:", x)
if x == 0:
    randomSeason = random.randint(1,13)
    print("Random season:", randomSeason)

    episode = random.randint(epRanges[randomSeason][0], epRanges[randomSeason][1])           
    print("Episode:", epTitles[randomSeason][episode-1])

答案 2 :(得分:0)

感谢所有建议!通过将所有情节放在一个字典中,并使用元组作为键,我可以大大缩短它。然后,我可以根据用户输入过滤出键,并打印出季节和剧集的标题