如果没有大量的if/elif/elif/,如何在代码中查找数据。。。条件?

2024-10-03 00:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的一个个人项目,现在我的程序是一吨如果语句的基础上,我做了每一季的集编号(不同的季节有不同的集数)和标题字典。我得到了想要的结果,但是我一直在努力寻找一种更高级的方法,比如使用函数、列表或对象来更优雅地显示它,并且代码行更少。你知道吗

我一直试图通过google和教程找出如何使用其他方法之一,但我不知道如何将其应用到我的特定程序中,在没有所有这些单独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) 

我只想学习和理解什么样的方法/方法可以帮助我以更实际的方式压缩代码,以及如何做到这一点。你知道吗


Tags: andthe方法ifrandomseasonprintelif
3条回答

将数据存储在一个dict的dict中。外文记载了季节,内文记载了本部分的零件号和名称:

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。你知道吗


为了让它成为用户输入的证明,而不是使用dict中的随机数:

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"

你可以这样做你的字典

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])

您还可以将随机选择的事件范围保存在一个元组的dict中,以进一步最小化代码,因此最终代码将如下所示

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])

谢谢你的建议!我把所有的片段放在一本字典里,用元组作为键,就可以大大缩短它。然后我就可以根据用户的输入过滤出按键,打印出这一季和这一集的标题

相关问题 更多 >